Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I see object values when debugging terraform

Tags:

terraform

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?

like image 209
Krist van Besien Avatar asked Apr 27 '26 05:04

Krist van Besien


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"
  },
]
like image 78
aditya Avatar answered Apr 30 '26 05:04

aditya


**** Warning: this could potentially write sensitive data to disk, use with caution ****

To see the contents of an object create a temporary local_file resource and set it's content property to the object converted to json. It will then be displayed in the plan. Once you are done remove the resource. For example:

resource "local_file" "this" {
    content  = jsonencode(your object)
    filename = "a valid file path"
}
like image 36
Eric Scherrer Avatar answered Apr 30 '26 05:04

Eric Scherrer