首页 > 解决方案 > 在资源本身使用 for_each 的资源的子元素中使用 for 循环进行插值

问题描述

例如,这里是使用 for_each 部署的资源(非常简化)(for_each 不是我遇到问题的地方,我可以整天这样做 - 它试图正确插入 ovf_network_map 中的数据是我遇到问题的地方):

resource "vsphere_virtual_machine" "vmFromLocalOvf" {
  for_each = var.customers[var.customer][var.idc].vms
  ...snip...
  ovf_deploy {
    local_ovf_path = "cucm_11.5_vmv8_v1.1.ovf"        
    ovf_network_map = {
      for net in ["INSIDE", "OUTSIDE"]:
      "eth${count.index}" => data.vsphere_network.net.id
    }

对于这个简化的示例,最终目标是 ovf_network_map 包含 { "eth0" = data.vsphere_network.INSIDE.id, "eth1" = data.vsphere_network.OUTSIDE.id } (显然,数据对象将被进一步插值那里,但希望我试图完成的问题在这里出现)。

有2个错误: The "count" object can be used only in "resource" and "data" blocks, and only when the "count" argument is set. 另外 A data resource "vsphere_network" "net" has not been declared,显然我的插值有错误。希望我在这里需要的插值是可能的-我可能以错误的方式进行此操作-有什么想法吗?

编辑添加:我已经能够计算出 eth0、eth1 的数字计数:eth${index(slice(var.customers[var.customer][var.idc].vms[each.key], 3, length(var.customers[var.customer][var.idc].vms[each.key]) - 1), net)}" => data.vsphere_network.net.id

所以现在剩下的就是 -data.vsphere_network.net.id当我遇到错误时,我坚持尝试“加倍”插入“网络”A data resource "vsphere_network" "net" has not been declared

标签: terraformterraform0.12+

解决方案


您不会在for_each中获得count变量或相应的count.index,因此这是行不通的:

resource "vsphere_virtual_machine" "vmFromLocalOvf" {
  for_each = var.customers[var.customer][var.idc].vms
  ...snip...
  ovf_deploy {
    local_ovf_path = "cucm_11.5_vmv8_v1.1.ovf"        
    ovf_network_map = {
      for net in ["INSIDE", "OUTSIDE"]:
      "eth${count.index}" => data.vsphere_network.net.id
    }

可以如下获取从索引到值的映射,然后像使用count.index一样使用each.key

resource "vsphere_virtual_machine" "vmFromLocalOvf" {
  for_each = zipmap(
    range(length(var.customers[var.customer][var.idc].vms)),
    var.customers[var.customer][var.idc].vms
  )
  ...snip...
  ovf_deploy {
    local_ovf_path = "cucm_11.5_vmv8_v1.1.ovf"        
    ovf_network_map = {
      for net in ["INSIDE", "OUTSIDE"]:
      "eth${each.key}" => data.vsphere_network.net.id
    }

推荐阅读