首页 > 解决方案 > 调试 terraform 时如何查看对象值

问题描述

在编写 terraform 模块时,我经常遇到如下错误:

Error: Invalid index

  on ../../../modules/host/main.tf line 7, in resource "aws_network_interface" "host":
   7:   subnet_id = data.aws_subnet_ids.current[each.key].ids[0]
    |----------------
    | data.aws_subnet_ids.current is object with 2 attributes
    | each.key is "lab"

发生这种情况的原因有很多。通常是因为我认为某个对象将包含的内容不正确。

为了帮助调试它,至少查看对象包含的内容会很有用。“具有 2 个属性的对象”相当模糊。我想知道它有什么属性,所以我可以添加必要的转换来最终得到我需要的字符串。

那么有没有办法呢?您能否以某种方式运行“terraform plan”,以便在计划遇到错误时实际显示这些对象的内容?

标签: terraform

解决方案


您可以运行“terraform console”命令并直接输入您的表达式。例如。假设对于变量文件中的给定地图,您希望查看扁平列表。

variable "podmap" {
   type  = "map"
   default = {
       dev = ["pod1", "pod6"]
       qa =  ["pod5"]
       uat = ["pod5"]
       testenv = []
  }
}

运行 terraform 控制台:

$ terraform console
> flatten([for podtype, podlist in var.podmap : [for podname in podlist : { name = podname, type = podtype }]])flatten([for podtype, podlist in var.podmap : [for podname in podlist : { name = podname, type = podtype }]])

根据您的表达/陈述,它将为您提供相应的输出。

对于上面的 flatten 功能,您将在执行 terraform plan 时看不到的输出列表下方。

[
  {
    "name" = "pod5"
    "type" = "dev"
  },
  {
    "name" = "pod6"
    "type" = "dev"
  },
  {
    "name" = "pod5"
    "type" = "qa"
  },
  {
    "name" = "pod5"
    "type" = "uat"
  },
]

推荐阅读