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

如何将Terraform模块的Map变量传入Resource实现for_each?

Terraform模块传递Map变量实现for_each批量创建实例

问题核心

你当前模块无法获取instance变量的原因是模块内未定义该变量,同时资源配置中存在一处属性取值错误。

步骤1:在模块中定义instance变量

在模块目录下创建variables.tf文件,明确声明接收的instance Map变量:

variable "instance" {
  type = map(object({
    instance_hostname = string
    instance_label    = string
    instance_tags     = list(string)
    ssh_key_name      = list(string)
    plan              = string
    os_id             = string
    label             = string
    enable_ipv6       = bool
    backups           = string
    backups_schedule  = string
    backups_dow       = number
    backups_hour      = number
    ddos_protection   = bool
    activation_email  = bool
  }))
  description = "Map of instances to provision"
  default     = {}
}

# 确保模块已定义其他依赖变量,比如region
variable "region" {
  type        = string
  description = "Target region for all instances"
}

步骤2:修正模块内资源的配置错误

你的vultr_instance资源中region = each.value.region是错误的——传入的instance Map里并没有region字段,该值是通过模块的region变量传递的,需要改为var.region:

resource "vultr_instance" "my_instance" {
  for_each          = var.instance
  plan              = each.value.plan
  region            = var.region  # 修正此处,使用模块级region变量
  os_id             = each.value.os_id
  label             = each.value.label
  tags              = each.value.instance_tags
  hostname          = each.value.instance_hostname
  firewall_group_id = vultr_firewall_group.firewallgroups.id
  vpc_ids           = [vultr_vpc.vpc.id]
  ssh_key_ids       = [data.vultr_ssh_key.ssh_key.id]
  enable_ipv6       = each.value.enable_ipv6
  ddos_protection   = each.value.ddos_protection
  activation_email  = each.value.activation_email
  backups           = each.value.backups
  backups_schedule {
    type = try(each.value.backups_schedule, null)
    dow  = try(each.value.backups_dow, null)
    hour = try(each.value.backups_hour, null)
  }
}

验证执行

完成修改后,执行以下命令确认配置生效:

  • terraform init:初始化模块与提供者
  • terraform plan:查看执行计划,确认将创建application和database两个实例
  • terraform apply:执行资源创建

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:55:31