terraform - 在资源本身使用 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
解决方案
您不会在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
}
推荐阅读
- node.js - 如何在 Laravel 8 中使用 SASS?
- python - 由于精度问题,python搜索浮点数返回错误?
- arduino - 我不知道我的代码有什么问题,随机发生的事情
- vue.js - Vuetify - 如何在自定义构建中禁用显示助手?
- javascript - 如何在特定时间后运行一个函数,该时间由点击之类的事件触发(原生 JavaScript)
- php - CakePHP 4 和 Authentication 2 插件 - 记住我不会创建 Cookie
- android - 尝试在空对象引用 (MessageActivity.java:150) 上调用虚拟方法“boolean java.lang.String.equals(java.lang.Object)”
- html - 构建后未找到 Angular 11 资产
- c# - Entity Framework 6 可以从分隔字符串列映射外键吗?
- asynchronous - 暂时挂起或停用 futures::select 中使用的间隔流