![](/img/trans.png)
[英]Unable to attach Public IP to Azure windows VM (created using for_each) in Terraform
[英]Azure VM Creation using For_Each loop via Terraform
我正在尝试通过 terrform 使用 for_each 创建多个 Azure VM,我能够创建 2 个 NIC 卡,但是在 zurerm_windows_virtual_machine 块中定义 NIC id 时,两个 VM 都选择相同的 NIC 卡(最后一个,索引 1),结果只有 VM被创建和其他失败。 (network_interface_ids = azurerm_network_interface.az_nic[*].id) 的逻辑是什么,第一个虚拟机将选择第一个网卡,第二个这样做。
#--------------为 Windows 虚拟机创建网络接口--------------
resource "azurerm_network_interface" "az_nic" {
count = length(var.vm_names)
name = "${var.vm_names[count.index]}_nic"
location = var.location
resource_group_name = data.azurerm_resource_group.Resource_group.name
ip_configuration {
name = var.vm_names[count.index]
subnet_id = data.azurerm_subnet.subnet.id
private_ip_address_allocation = "Dynamic"
}
}
resource "azurerm_windows_virtual_machine" "myvm" {
for_each = toset(var.vm_names)
name = each.value
resource_group_name = data.azurerm_resource_group.Resource_group.name
location = var.location
size = "Standard_D2s_v3"
admin_username = "abc"
admin_password = "uejehrikch123"
network_interface_ids = azurerm_network_interface.az_nic[*].id
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2016-Datacenter"
version = "latest"
}
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
您可以在resource "azurerm_windows_virtual_machine"
添加count
参数,而不是混合count
和for_each
。
假设你有
variable "vm_names" {
default = ["vm1", "vm2"]
}
然后你可以像这样更改资源.tf
文件:
resource "azurerm_windows_virtual_machine" "myvm" {
count = length(var.vm_names)
name = element(var.vm_names,count.index)
resource_group_name = data.azurerm_resource_group.Resource_group.name
location = var.location
size = "Standard_D2s_v3"
admin_username = "abc"
admin_password = "uejehrikch123"
network_interface_ids = [element(azurerm_network_interface.az_nic.*.id, count.index)]
source_image_reference {
publisher = "MicrosoftWindowsServer"
offer = "WindowsServer"
sku = "2016-Datacenter"
version = "latest"
}
os_disk {
caching = "ReadWrite"
storage_account_type = "Standard_LRS"
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.