How to debug print terraform variable values when the plan step fails

I’m reviving an old terraform script where a variable caused the plan step to fail. How to debug print such terraform variable values during it run?

$ terraform console
> var.name
"demo"

$ make apply
terraform apply

│ Error: "name" may only contain alphanumeric characters, dots, dashes and underscores
│ 
│   with module.linux.azurerm_linux_virtual_machine.mytfvm,
│   on linux/main.tf line 80, in resource "azurerm_linux_virtual_machine" "mytfvm":
│   80:   name                  = "${var.name}"
│ 
╵
╷
│ Error: "name" must begin with an alphanumeric character
│ 
│   with module.linux.azurerm_linux_virtual_machine.mytfvm,
│   on linux/main.tf line 80, in resource "azurerm_linux_virtual_machine" "mytfvm":
│   80:   name                  = "${var.name}"
│ 
╵
╷
│ Error: "name" must end with an alphanumeric character or underscore
│ 
│   with module.linux.azurerm_linux_virtual_machine.mytfvm,
│   on linux/main.tf line 80, in resource "azurerm_linux_virtual_machine" "mytfvm":
│   80:   name                  = "${var.name}"
│ 
╵
╷
│ Error: "computer_name" cannot contain the special characters: `\/"[]:|<>+=;,?*@&~!#$%^()_{}'`
│ 
│   with module.linux.azurerm_linux_virtual_machine.mytfvm,
│   on linux/main.tf line 88, in resource "azurerm_linux_virtual_machine" "mytfvm":
│   88:   computer_name  = "${var.name}"

You can see that the var.name prints fine during terraform console, but somehow get changed strangely during the terraform execution from the complicated old terraform script. So,

How to debug print terraform variable values during terraform execution?

Recent versions of Terraform have improved the error diagnostics to display the values for references in diagnostic error messages. Which version of Terraform are you using?

One thing to note here is that the var.name in this example is in the context of module.linux, and depending on your module call may not be equal to the var.name value in the root module. I’d recommend checking your module call block to see what the value of the name argument is.

thanks for your reply.

I think mine is already the latest:

$ apt-cache policy terraform
terraform:
  Installed: 1.2.2
  Candidate: 1.2.2
  Version table:
 *** 1.2.2 100
         80 https://apt.releases.hashicorp.com bullseye/main amd64 Packages
        100 /var/lib/dpkg/status

I’m quite new to terraform, so how to check my module call block to see what the value of the name argument is.

In linux/variables.tf file, I have

variable "name" {}

and most importantly, how can I set its value before/during terraform execution?

Look for the block of code which calls this module in your root module. Something like:

module "az_linux_vm" {
  source = "./linux"
  name = local.some_value_for_name
}

This is what defines what value the linux module receives for name, which then causes the errors you’re seeing above.

1 Like