地形资源的可变性

时间:2018-01-16 11:23:59

标签: azure terraform terraform-provider-azure

我尝试在terraform中创建一个基于列表变量创建多个子网的资源。

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

Glyph

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

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

由于缺乏可变插值支持,我无法猜测。

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

1 个答案:

答案 0 :(得分: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