【问题标题】:terraform get index value from the listterraform 从列表中获取索引值
【发布时间】:2021-10-06 14:07:53
【问题描述】:

如何将索引值分配给 terraform 变量

让我们说:

我的示例输入看起来, terraform.tfvars.json:

{
    "resource_groups": [
        {
            "name_suffix": "AI",
            "location": "westus2",
            "is_default": false
        },
        {
            "name_suffix": "Montoring",
            "location": "westus2",
            "is_default": false
        },
        {
            "name_suffix": "Base",
            "location": "westus2",
            "is_default": false
        },
        {
            "name_suffix": "Core",
            "location": "westus2",
            "is_default": true
        }

    ]
}

main.tf

 locals {
 # I tried like 

 default_rg_index = [for rg, index in var.resource_groups: index if try(rg.is_default, false) == true]
}

我希望 default_rg_index 分配 3,但它不起作用

【问题讨论】:

  • [{rg_name: "a", is_default: false, {rg_name: "b", is_default: true}] 是无效的 TF 代码。你能提供有效的例子吗?
  • 好的,我在 json 中的输入,让我在 hcl 中为您提供
  • 这也是无效的json。
  • 我修好了。我猜到了你想要什么。
  • 刚刚添加,完整输入

标签: terraform hcl


【解决方案1】:

rg, index 应该相反。你也可以让它更简单:

default_rg_index = [for index, rg in var.resource_groups: index if rg.is_default]

【讨论】:

  • 会返回列表类型还是数字类型?
  • @Vidya 列表。您可以使用default_rg_index[0] 来获取值。或将 [0] 附加到 [for index, rg in var.resource_groups: index if rg.is_default]
猜你喜欢
  • 2020-08-04
  • 1970-01-01
  • 2013-03-30
  • 1970-01-01
  • 1970-01-01
  • 2019-01-29
  • 2021-09-20
  • 2014-02-06
  • 2020-04-01
相关资源
最近更新 更多