我正在配置 Terraform 以在 VMware 中配置虚拟机。每个 VM 都将分配一个与特定 VLAN 连接的第二个网络适配器。根据虚拟机名称分配VLAN
数据源似乎可以很好地查询,因为它们都存在。但是,我无法将 count.index 传递到 network_interface 部分的 network_id 中。 我已经尝试过以下方法:
network_id = "${data.vsphere_network.network1."${var.policy_name}".id}"
network_id = "${"${format("%s", "data.vsphere_network.network1.${count.index}.id")}"}"
network_id = "${format("%s", "$${data.vsphere_network.network1.${count.index}.id")}"
唯一可行的方法是直接赋值:
network_id = "${data.vsphere_network.network1.0.id}"
其中 0 是实例。
data "vsphere_network" "network1" {
count = "${var.count}"
name = "${var.network_name1}-${format("%02d", count.index + var.start_index)}"
datacenter_id = "${data.vsphere_datacenter.datacenter.id}"
}
network_interface {
network_id = "${data.vsphere_network.network1.0.id}"
adapter_type = "vmxnet3"
use_static_mac = "${var.static_mac}"
}
我希望 VLAN 01 分配给 VM01。 VLAN 02 分配给 VM02,一直到 48(因为这是我拥有的 VLAN 的数量)
最佳答案
以下示例使用 Terraform 0.12 功能来声明每个网络应该有一个实例,并通过其网络 ID 标识每个实例,以便将来添加和删除网络也会导致添加/删除适当的实例:
data "vsphere_network" "network1" {
count = var.count
name = "${var.network_name1}-${format("%02d", count.index + var.start_index)}"
datacenter_id = data.vsphere_datacenter.datacenter.id
}
resource "vsphere_virtual_machine" "per_network" {
# Create one VM per network and identify them using the
# id value of each one.
for_each = { for net in data.vsphere_network.network1 : net.id => net }
# (...other virtual machine arguments...)
network_interface {
# each.key is the key from the map in for_each, which is
# the network id in this case
network_id = each.key
}
}
在这里使用 for_each
有两个主要优点:
它让 future 的读者更清楚,其目的是为每个网络创建一个 VM,因为在
for_each
表达式中直接引用了网络数据资源。它允许您选择 Terraform 在跟踪状态中的每个实例时用来识别每个实例的键。因为在这种情况下,虚拟机由它们的网络唯一标识,所以我们使用网络接口(interface) ID,因此 Terraform 将能够正确地推断出例如添加新网络应该会导致创建新的 VM,而删除网络应该只会导致相应的 VM 被销毁。
关于Terraform 插值数据源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57480140/