如何将随机subnet_id分配给azurerm_network_interface?

问题描述 投票:1回答:2
### 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个VM分为3个子网,例如,子网A = 2个VM,子网B = 2个VM,子网C = 3个VM或随机``错误:错误:索引无效

在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 

azure sdn terraform-provider-azure
2个回答
0
投票

“ vm-count”是您所遇到的问题。您的变量“ vm-subnets”具有3个项目,但是您将变量“ vm-count”设置为5。注意“ azurerm_network_interface”正在“ vm-count”(具有5个索引)上循环,而您只有3个“ azurerm_subnet”索引”。因此,将变量“ vm-count”设置为3,否则在列表“ vm-subnets”中再创建两个子网。


0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.