【问题标题】:Terraform get the length of listTerraform 获取列表的长度
【发布时间】:2017-11-03 23:47:36
【问题描述】:

我正在试验 Terraform,我遇到了 本地人。我要做的是根据另一个变量(env)获取列表的长度。

在尝试评估长度之前如何使 terrform 评估变量?

这是我的代码:

locals {
  env = "${terraform.workspace}"

  subnet_names = {
    "default" = ["default_sub1"]
    "dev"     = ["dev_sub1", "dev_sub2", "dev_sub3"]
    "prod"    = ["prod_sub1", "prod_sub2", "prod_sub3"]
  }

}

resource "azurerm_subnet" "subnet" {
  name                      = "${lookup(local.subnet_names, local.env, count.index)}"
  virtual_network_name      = "${azurerm_virtual_network.network.name}"
  resource_group_name       = "${azurerm_resource_group.terraform.name}"
  address_prefix            = "10.0.1.0/24"
  network_security_group_id = "${azurerm_network_security_group.security_group.id}"
  count                     =  "${length(local.subnet_names, local.env)}"
}

当我尝试验证代码时,我得到了 length: expected 1 arguments, got 2 in: ${length(local.subnet_names, local.env)}

这里有什么诀窍?

【问题讨论】:

    标签: terraform


    【解决方案1】:

    您的local.subnet_names 不是一个列表,它是一个map,可以按照interpolation syntax 中的说明进行访问:

    ${length(local.subnet_names[local.env])}
    

    编辑:

    至于name变量,正确的制作方法是使用element插值:

    name = "${element(local.subnet_names[local.env], count.index)}"
    

    这是因为local.subnet_names[local.env] 将返回一个列表。例如,如果local.env 是“dev”,它将返回

    ["dev_sub1", "dev_sub2", "dev_sub3"]
    

    要获取列表中某个索引中的元素,我们使用element

    【讨论】:

    • 谢谢,我现在又遇到一个错误 :(,你会怎么做原始示例中的 name = "${lookup(local.subnet_names, local.env, count.index)}" 现在抛出错误 azurerm_subnet.subnet[1]: lookup: lookup() may only be used with flat maps, this map contains elements of type list in
    • 不是您问题的答案,只是想指出terraform.io/docs/commands/console.html 在尝试计算出所有 terraform 插值函数的正确组合时非常有用
    猜你喜欢
    • 2019-02-02
    • 2022-11-14
    • 1970-01-01
    • 2015-11-20
    • 2021-07-25
    • 1970-01-01
    • 2013-12-07
    • 1970-01-01
    • 2017-06-30
    相关资源
    最近更新 更多