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

如何使用Terraform的for_each创建多台配置不同的vSphere虚拟机

问题排查
  • tfvars配置语法错误:example_users作为map类型变量,键值对格式不符合HCL规范,缺少键与值之间的等号,存在多余的逗号分隔符
  • 属性名拼写错误:main.tf中读取内存配置时将hardware错写为harware,会触发属性不存在的运行报错
  • 缺少变量声明:未提前定义example_users变量的类型结构,Terraform无法识别变量内部的嵌套属性
完整实现方案

1. 新增variables.tf定义变量约束

variable "example_users" {
  type = map(object({
    hardware = object({
      cpus   = number
      memory = number # 此处单位可自行约定,建议用GB,后续计算时转换为vSphere要求的MB
    })
  }))
  description = "不同用户对应的虚拟机硬件配置"
}

2. 修正terraform.tfvars配置

example_users = {
  name1 = {
    hardware = {
      cpus   = 8
      memory = 10 # 单位GB
    }
  },
  name2 = {
    hardware = {
      cpus   = 9
      memory = 8 # 单位GB
    }
  }
  # 其余用户按相同格式追加即可
}

3. 修正main.tf虚拟机资源配置

resource "vsphere_virtual_machine" "user_vm" {
  for_each = var.example_users

  # 虚拟机名称用对应用户名
  name   = each.key
  cpus   = each.value.hardware.cpus
  memory = each.value.hardware.memory * 1024 # 转换为vSphere要求的MB单位

  # 其余vSphere虚拟机必填配置(比如datastore、network、guest_id、克隆的模板等)按实际环境补充即可
  # ...
}
注意事项
  • 配置中的内存单位如果已经是MB,可去掉*1024的转换逻辑
  • 执行部署前可先运行terraform plan检查配置是否正确,无报错再执行terraform apply

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 19:18:02