如何将随机 subnet_id 分配给 azurerm_network_interface?

How do I assign random subnet_id into azurerm_network_interface?

### variable
variable "vm-subnets" { 
  type = list(string) 
  default = ["7.0.1.0/24","7.0.2.0/24","7.0.3.0/24"] 
}

### subnet
resource "azurerm_subnet" "task_subnet" {
  name                 = "subnet-${format("%02d",count.index)}"
  resource_group_name  = azurerm_resource_group.task.name
  virtual_network_name = azurerm_virtual_network.task_vnet.name
  network_security_group_id = azurerm_network_security_group.task_nsg.id
  address_prefix       = var.vm-subnets[count.index]
  count                 = length(var.vm-subnets)
}

### NIC
resource "azurerm_network_interface" "vm_nic" {
  name                = "nic--${format("%02d",count.index)}"
  location            = var.region
  resource_group_name = azurerm_resource_group.task.name
  count               = var.vm-count

  ip_configuration {
    name                          = "${var.resource_prefix}-${format("%02d",count.index)}-ip"
    subnet_id                     = azurerm_subnet.task_subnet.*.id[count.index]
    private_ip_address_allocation = "dynamic"
    public_ip_address_id          = azurerm_public_ip.task_public_ip.*.id[count.index]
  }<br>
}

我需要将 7 个虚拟机放入 3 个子网中,例如子网-A = 2 个虚拟机,子网-B = 2 个虚拟机,子网-C = 3 个虚拟机或随机 `` 错误: 错误:无效索引

在 vm-network.tf 第 11 行,在资源 "azurerm_network_interface" "vm_nic" 中: 11: subnet_id = azurerm_subnet.task_subnet.*.id[count.index] |---------------- | azurerm_subnet.task_subnet 是包含 3 个元素的元组 | count.index 是 4

给定键未标识此集合值中的元素。

错误:索引无效

在 vm-network.tf 第 11 行,在资源 "azurerm_network_interface" "vm_nic" 中: 11: subnet_id = azurerm_subnet.task_subnet.*.id[count.index] |---------------- | azurerm_subnet.task_subnet 是包含 3 个元素的元组 | count.index 是 3


The given key does not identify an element in this collection value.



What modification can be done to resolve it and how can I assign different/random subnet on each vm rather then count loop.

I also try to do it using random_shuffle and set-product function but not get the desired output .. please Help 

经过 2 天的逻辑斗争,我终于找到了解决方案或我创建的问题:使用元素函数 https://www.terraform.io/docs/configuration/functions/element.html

网卡

resource "azurerm_network_interface" "vm_nic" {
  name                = "nic--${format("%02d",count.index)}"
  location            = var.region
  resource_group_name = azurerm_resource_group.task.name
  count               = var.vm-count
  ip_configuration {
    name                          = "${var.resource_prefix}-${format("%02d",count.index)}-ip"
    subnet_id                     =  element(azurerm_subnet.task_subnet.*.id, count.index)
    private_ip_address_allocation = "dynamic"
    public_ip_address_id          = azurerm_public_ip.task_public_ip.*.id[count.index]
  }
} 
subnet_id =  element(azurerm_subnet.task_subnet.*.id, count.index)

在 vm count.index = 3 处使用元素函数 ["7.0.1.0/24","7.0.2.0/24","7.0.3.0/24"] 它返回到子网索引 = 0以便它如何工作并在 vm.count = 5, 7, 10 进行测试。✌