gpt4 book ai didi

通过 Terraform 使用 For_Each 循环创建 Azure VM

转载 作者:行者123 更新时间:2023-12-02 07:56:36 28 4
gpt4 key购买 nike

我正在尝试通过 terrform 使用 for_each 创建多个 Azure VM,我能够创建 2 个 NIC 卡,但是在 zurerm_windows_virtual_machine block 中定义 NIC id 时,两个 VM 都选择相同的 NIC 卡(最后一个,索引 1),结果是只有虚拟机正在创建,其他虚拟机失败。(network_interface_ids = azurerm_network_interface.az_nic[*].id) 的逻辑是什么:第一个虚拟机将选择第一个网卡,第二个虚拟机也这样做。

#---------------为 Windows VM 创建网络接口(interface) --------------

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"
}

最佳答案

您可以在资源“azurerm_windows_virtual_machine”中添加count参数,而不是混合使用countfor_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"
}

关于通过 Terraform 使用 For_Each 循环创建 Azure VM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64467921/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com