How do I see object values when debugging terraform

Viewed 4658

When writing a terraform module I often run in errors like this:

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"

There are all kinds of reasons why this happens. Usually it is because what I think a certain object will contain is incorrect.

In order to help debugging this it would be usefull to at least see what the object contains. "Object with 2 attributes" is rather vague. I would like to know what attribtues it has, so I can add the necessary transformations to end up with the string I need here.

So is there a way? Can you in some way run "terraform plan" in such that the contents of those objects are actually displayed when the plan runs in to an error?

2 Answers

You can run "terraform console" command and put directly your expressions. eg. Suppose for given map in variable file you want to see flattened list.

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

Run terraform console:

$ 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 }]])

Based on your expression/statement it will give you output accordingly.

for above flatten function you will get below output list which you cannot see while you do terraform plan.

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

This turned to be actually easier than I expected.

Just do:

terraform refresh
terraform show

And you will see what all current data sources contain.

It would have been convenient if this possibility was hinted at under the debugging chapter of the docs...

Related