Convert HCL into JSON


For some reason I need/want to use .tf.json file, and I need help with some conversation.

I have variable with validation block, and i don’t know how to convert condition section into string?

validation {
    condition     = var.hardware_backend == "vsphere" || var.hardware_backend == "vcloud"
    error_message = "..."

Hi @skydion,

Terraform interprets condition as a normal expression (albeit with additional constraints about what objects you can refer to in it) and so the JSON representation of it is the typical JSON expression mapping, which involves changing the expression into a string template containing only a single interpolation sequence:

  "condition": "${var.hardware_backend == \"vsphere\" || var.hardware_backend == \"vcloud\"}"

Notice that in order for the result to be a valid JSON string I also had to escape the quotes inside the expression. When decoding this, Terraform will:

  • Interpret the condition value as a JSON string, to obtain ${var.hardware_backend == "vsphere" || var.hardware_backend == "vcloud"}
  • Parse that result as a Terraform string template, producing a template expression.
  • Evaluate the template expression with var.hardware_backend available, yielding either true or false as the result.
  • Use that boolean result to decide whether the condition is satisfied.

It work, thank you for explanation @apparentlymart