How to debug Terraform variable content using this custom module

A lot of the time when I’m having to debug Terraform, I find that I want to quickly look at what Terraform may be storing inside a variable so that I can understand where I’ve made a mistake passing data around. After literal years of using the old TF_LOG=debug method – which can get way too unwieldy with any decently sized environment, I realized I could write a simple module to dump out what I was looking for. Hopefully this will help you too.

resource "null_resource" "terraform-debug" {
  provisioner "local-exec" {
    command = "echo $VARIABLE1 >> debug.txt ; echo $VARIABLE2 >> debug.txt"

    environment = {
        VARIABLE1 = jsonencode(var.your_variable_name)
        VARIABLE2 = jsonencode(local.piece_of_data)
    }
  }
}

Just replace var.your_variable_name_goes_here with your actual variable reference and then run your terraform apply. A file should be spit out in the same directory that the .tf file that you inserted this resource lives in, which you can then open up and understand what might be going on.

I don’t know why it took me so long to figure out something so simple, but coming from PHP/Laravel – where you can just dd() or dump() the contents of a variable to the console – the idea of using the local-exec provisioner to debug terraform just never occurred to me.

EDIT [Jan 6, 2020]: Wrapped variable data in jsonencode() to avoid issues with echoing an empty string to a file. Also show how to dump multiple variables to the same file.