You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Terraform为GCP有状态托管实例组分配静态内部IP

为GCP有状态托管实例组(MIG)分配静态内部IP的Terraform实现

要实现按可用区为MIG内的每台VM绑定静态内部IP,你需要先为每个节点创建静态内部IP资源,再通过google_compute_region_per_instance_config的preserved_state字段绑定IP(当前Terraform GCP Provider已支持该配置,可覆盖你之前查阅文档的限制)。以下是完整修改后的代码:

1. 定义节点映射与静态内部IP资源

首先扩展节点可用区映射,并为每个节点创建对应可用区的静态内部IP:

locals {
  node_zone_mapping = {
    "git-1" = "us-central1-a",
    "git-2" = "us-central1-b",
    "git-3" = "us-central1-c"
  }
  short_ver = "v1" # 保持你现有代码中的版本标识
}

# 为每个节点创建静态内部IP
resource "google_compute_address" "git_static_ip" {
  for_each      = local.node_zone_mapping
  name          = format("exp-git-static-ip-%s", each.key)
  region        = "us-central1"
  subnetwork    = "your-subnetwork-name" # 替换为你的子网名称
  address_type  = "INTERNAL"
  zone          = each.value # 静态IP与节点同可用区
}

2. 更新MIG配置

调整MIG的目标实例数和可用区列表,同时确保禁止实例跨区迁移:

// Create instance group manager for gitaly nodes
resource "google_compute_region_instance_group_manager" "git-server-mig" {
  description = "Terraform test instance group manager"
  name        = "exp-manage-git-mig"

  version {
    instance_template = google_compute_instance_template.git-server.self_link
  }

  update_policy {
    type                         = "OPPORTUNISTIC"
    instance_redistribution_type = "NONE" # 关键:禁止实例跨可用区重分配
    minimal_action               = "REPLACE"
    max_unavailable_fixed        = 2
  }

  base_instance_name        = "exp-git-server"
  region                    = "us-central1"
  target_size               = 3 # 对应3台VM
  distribution_policy_zones = ["us-central1-a", "us-central1-b", "us-central1-c"]
}

3. 扩展实例状态配置(绑定磁盘+静态IP)

修改google_compute_region_per_instance_config,在preserved_state中添加静态IP绑定:

// define state config for MIG (preserve disk and static internal IP)
resource "google_compute_region_per_instance_config" "preserve_gitaly_state" {
  for_each = local.node_zone_mapping
  region                      = "us-central1"
  region_instance_group_manager = google_compute_region_instance_group_manager.git-server-mig.name
  name                        = format("exp-%s-%s", each.key, local.short_ver)
  
  preserved_state {
    // 保留原有磁盘绑定配置
    disk {
      device_name = format("exp-disk-%s-%s", each.key, local.short_ver)
      source      = google_compute_disk.git-disk[each.key].self_link
      mode        = "READ_WRITE"
    }

    // 添加静态内部IP绑定
    internal_ip {
      ip_address = google_compute_address.git_static_ip[each.key].address
    }
  }
}

关键注意事项

  • 可用区一致性:静态IP必须与对应实例处于同一个可用区,否则无法完成绑定
  • 禁止跨区迁移:instance_redistribution_type = "NONE"是核心配置,确保MIG不会将实例迁移到其他可用区,避免IP与实例不匹配
  • 子网匹配:静态IP的子网必须与实例模板中配置的子网一致
  • 状态保留机制:当MIG执行实例替换时,preserved_state会自动将原磁盘和静态IP绑定到新实例,保证服务连续性

内容的提问来源于stack exchange,提问作者anujkum

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 21:55:44