Skip to content

Terraform Google Managed Instance Group (MIG)#

This Terraform module creates a Managed Instance Group (MIG) on Google Cloud Platform. It provides a flexible way to deploy and manage a fleet of virtual machines with autoscaling and an optional external HTTPS load balancer.

Compatibility#

This module is compatible with Terraform version ~> 1.0 and has been tested with the following provider versions:

  • Google Provider: >= 6.28.0, < 7.0.0
  • Google Beta Provider: >= 6.28.0, < 7.0.0

Features#

  • Managed Instance Group (MIG): Deploys a regional MIG with a configurable instance template.
  • Customizable Instances: Control machine type, disk size, source image, and more.
  • Service Account: Creates a dedicated IAM service account for the instances with configurable project roles.
  • Autoscaling: Supports CPU-based, metric-based, and scheduled autoscaling.
  • External Load Balancer: Optionally creates an external HTTPS load balancer with a managed SSL certificate and forwards traffic to the MIG.
  • IAP Access: Configures IAP (Identity-Aware Proxy) for secure SSH/RDP access to instances.

Usage#

Here's a basic example of how to use the module:

module "mig" {
  source  = "path/to/this/module"

  project_id      = "acme-prod-shared-vpc"
  region          = "me-west1"
  name            = "mig-prod-me-west1"
  name_prefix     = "mig-prod-me-west1"
  network_name    = "shared-vpc-network"
  subnet_link     = "/projects/acme-prod-shared-vpc/regions/me-west1/subnetworks/sql-proxy-shared-prod-me-west1"
  service_account = "mig-prod"
  iap_user_list   = ["gcp-admin-acme@example.com"]
  labels = {
    "owner"       = "company",
    "environment" = "prod"
  }
  autoscaling_enabled = "true"

  iam_project_roles = ["roles/iap.tunnelResourceAccessor", "roles/compute.instanceAdmin.v1"]
  startup_script    = <<-EOT
  # Install and start Nginx
  yum install -y nginx
  systemctl enable nginx
  systemctl start nginx
  EOT

  # External Load Balancer Example
  create_lb            = false
  lb_name              = "my-mig-lb"
  lb_domains           = ["nip.io"]
  lb_health_check_path = "/"

}

Terragrunt Usage#

This module is designed to work with Terragrunt. The startup_script should be provided using the templatefile function in your terragrunt.hcl file. See terragrunt.hcl.tmpl for a detailed example.

inputs = {
  # ... other inputs
  startup_script = templatefile("${get_terragrunt_dir()}/userdata.tmpl", {})
}

Limitations#

  • Load Balancer: The module currently only supports creating an external HTTPS load balancer. Internal load balancers or other types are not supported. It creates Classic External Load Balancer
  • Health Checks: The load balancer health check is basic. For complex health checking logic, you might need to create the health check resource outside of this module and pass it in.

Software#

This module requires the following software dependencies:

Service Account#

The service account used to run this module must have the following IAM roles:

  • roles/compute.admin - To create and manage Compute Engine resources
  • roles/iam.serviceAccountAdmin - To create and manage service accounts
  • roles/iam.serviceAccountUser - To use service accounts
  • roles/iap.admin - To configure Identity-Aware Proxy (when using IAP)

APIs#

The following GCP APIs must be enabled in the target project:

  • Compute Engine API (compute.googleapis.com)
  • Cloud Resource Manager API (cloudresourcemanager.googleapis.com)
  • Identity and Access Management (IAM) API (iam.googleapis.com)
  • Cloud Identity-Aware Proxy API (iap.googleapis.com) - Required when using IAP

License#

This module is covered by a commercial license. Please see LICENSE for details.

Support#

This module is developed and maintained by MyOps Limited. For any support inquiries, please contact us at info@myops.co.il.

Requirements#

Name Version
terraform ~> 1
google >= 6.28.0, < 7.0.0
google-beta >= 6.28.0, < 7.0.0

Providers#

No providers.

Modules#

Name Source Version
gce-lb-http terraform-google-modules/lb-http/google ~> 13.0.0
instance_template terraform-google-modules/vm/google//modules/instance_template ~> 13.0.0
mig terraform-google-modules/vm/google//modules/mig ~> 13.0.0
project_iam terraform-google-modules/iam/google//modules/projects_iam ~> 8.0.0
service-account git::https://github.com/GoogleCloudPlatform/cloud-foundation-fabric.git//modules/iam-service-account v38.1.0

Resources#

No resources.

Inputs#

Name Description Type Default Required
autoscaling_cpu The target CPU utilization for the autoscaler.
list(object({
target = number
predictive_method = string
}))
[] no
autoscaling_enabled If true, autoscaling is enabled for the MIG. string "false" no
autoscaling_metric The metric to use for autoscaling.
list(object({
name = string
target = number
type = string
}))
[] no
cooldown_period The number of seconds to wait after a scaling event before starting another one. number 60 no
create_lb If true, creates an external HTTPS load balancer for the MIG. bool false no
disk_encryption_key The self_link of the encryption key that is stored in KMS. string null no
disk_resource_policies A list of resource policy names to apply to the disks. list(string) [] no
disk_size_gb The size of the image in gigabytes. string "100" no
disk_type The GCE disk type. Can be pd-standard, pd-balanced, pd-ssd, local-ssd. string "pd-standard" no
distribution_policy_target_shape The target shape of the MIG. Can be EVEN, BALANCED, ANY. string null no
distribution_policy_zones The zones in which the instances will be created.Default is all zones in the region list(string) [] no
gpu GPU to attach to the instance.
object({
type = string
count = number
})
null no
health_check The health check to use for the MIG.
object({
type = string
initial_delay_sec = number
check_interval_sec = number
healthy_threshold = number
timeout_sec = number
unhealthy_threshold = number
response = string
proxy_header = string
port = number
request = string
request_path = string
host = string
enable_logging = bool
})
{
"check_interval_sec": 30,
"enable_logging": false,
"healthy_threshold": 1,
"host": "",
"initial_delay_sec": 30,
"port": 80,
"proxy_header": "NONE",
"request": "",
"request_path": "/",
"response": "",
"timeout_sec": 10,
"type": "",
"unhealthy_threshold": 5
}
no
iam_project_roles Project roles to assign to the service account list(string) [] no
iap_user_list List of users that will have access via IAP list(string) n/a yes
labels Labels, provided as a map map(string) {} no
lb_domains List of domains for the SSL certificate. list(string) [] no
lb_health_check_path The request path for the load balancer health check. string "/" no
lb_name Name to use for the load balancer resources. string "" no
machine_type Machine type to use for the proxy string "e2-standard-2" no
max_replicas The maximum number of replicas for the autoscaler. number 10 no
min_replicas The minimum number of replicas for the autoscaler. number 1 no
name Please provide instance name string "sql-proxy" no
name_prefix Please provide instance prefix string n/a yes
network_ip The private IP address to assign to the instance string "" no
network_name Name of the network where firewall rules will be created by LB string "" no
preemptible If true, instances will be preemptible. bool false no
project_id Please provide instance project string n/a yes
region Please provide instance region string n/a yes
scaling_schedules Autoscaling, scaling schedule block. https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/compute_autoscaler#scaling_schedules
list(object({
disabled = bool
duration_sec = number
min_required_replicas = number
name = string
schedule = string
time_zone = string
}))
[] no
service_account Service account to create to attach to the instance. See https://www.terraform.io/docs/providers/google/r/compute_instance_template.html#service_account. string n/a yes
source_image The source image to create the disk from. string "" no
source_image_project The project ID that the source image belongs to. string "rocky-linux-cloud" no
spot If true, instances will be spot VMs. bool false no
spot_instance_termination_action The action to take when a spot VM is terminated. string "STOP" no
startup_script User data script to run on instance startup. string n/a yes
stateful_disks Disks created on the instances that will be preserved on instance delete. https://cloud.google.com/compute/docs/instance-groups/configuring-stateful-disks-in-migs
list(object({
device_name = string
delete_rule = string
}))
[] no
stateful_ips Statful IPs created on the instances that will be preserved on instance delete. https://cloud.google.com/compute/docs/instance-groups/configuring-stateful-ip-addresses-in-migs
list(object({
interface_name = string
delete_rule = string
is_external = bool
}))
[] no
subnet_link Subnet link string n/a yes
tags Tags, provided as a map list(string) [] no
target_pools The target load balancing pools to assign this group to list(string) [] no
target_size n/a number 1 no
update_policy The rolling update policy. https://www.terraform.io/docs/providers/google/r/compute_region_instance_group_manager#rolling_update_policy
list(object({
max_surge_fixed = optional(number)
instance_redistribution_type = optional(string)
max_surge_percent = optional(number)
max_unavailable_fixed = optional(number)
max_unavailable_percent = optional(number)
min_ready_sec = optional(number)
replacement_method = optional(string)
minimal_action = string
type = string
most_disruptive_allowed_action = optional(string)
}))
[] no

Outputs#

Name Description
instances n/a
load_balancer_ip_address The IP address of the external load balancer.