0

我正在尝试在 terraform 中创建一个资源,它将根据列表变量创建许多子网。

我在引用现有资源时遇到问题。例如,在以下代码中,network_security_group_id 被硬编码为 azurerm_network_security_group.k8s.id:

variable "resources_large" {
    description = "List of Large Networks" 
    default = [
      "k8s",
      "storm"
    ]
}

resource "azurerm_subnet" "large" {
  name                      = "ue-${var.environment}-${var.resources_large[count.index]}-subnet-${replace("${cidrsubnet("${local.subnet_ranges["large"]}", "${var.newbit_size["large"] }", count.index )}", "/[./]/", "-"  ) }"
  resource_group_name       = "ue-${var.environment}-${var.resources_large[count.index]}-rg"
  virtual_network_name      = "${azurerm_virtual_network.dev.name}"
  address_prefix            = "${cidrsubnet("${local.subnet_ranges["large"]}", "${var.newbit_size["large"] }", count.index )}"
  network_security_group_id = "${azurerm_network_security_group.k8s.id}"

  count  = "${length(var.resources_large)}"

  depends_on = ["azurerm_virtual_network.dev"]
}

这需要根据 resources_large 列表中的名称引用现有的安全组。我想要的是看起来像这样的东西:

network_security_group_id = "${azurerm_network_security_group.${var.resources_large[count.index]}.id}"

这不起作用,我猜是由于缺乏变量插值支持。

有没有办法根据变量引用其他资源?

4

1 回答 1

1

也许是这样的

locals {
  sgs = {
    k8s = "${azurerm_network_security_group.k8s.id}"
    storm = "${azurerm_network_security_group.storm.id}"
  }
}

...

network_security_group_id = "${lookup( locals.sgs, var.resources_large[count.index])}"

可能工作。

如果您使用相同的计数器创建 SG,它可以只是

network_security_group_id = "${element(azurerm_network_security_group.*.id, count.index)}"

HTH

于 2018-01-16T14:22:14.003 回答