2

I have a Go project where I want to read a HCL file. This HCL file contains variables. However, I cannot parse it and I get the following error message:

Variables not allowed; Variables may not be used here., and 1 other diagnostic(s)

My Go Code:

package main

import (
    "fmt"
    "log"

    "github.com/hashicorp/hcl/v2/hclsimple"
)

type Config struct {
    Hello   string `hcl:"hello"`
    World   string `hcl:"world"`
    Message string `hcl:"message"`
}


func main() {
    var config Config
    err := hclsimple.DecodeFile("test.hcl", nil, &config)
    if err != nil {
        log.Fatalf("Failed to load configuration: %s", err)
    }
    fmt.Println(config.Message)
}

My HCL File

hello = "hello"
world = "world"
message = "hello ${world}"

What am I doing wrong? Is my HCL syntax perhaps not correct?

matt-rock
  • 133
  • 2
  • 14

1 Answers1

3

Is my HCL syntax perhaps not correct?

It's syntactically valid but doesn't work the way you're expecting it to. HCL doesn't allow for referencing arbitrary values defined elsewhere in the HCL file. It allows only for referencing variables which are exposed by the parser. For example, this gives the expected output:

ectx := &hcl.EvalContext{Variables: map[string]cty.Value{"world": cty.StringVal("world")}}
err := hclsimple.DecodeFile("test.hcl", ectx, &config)

The documentation doesn't make this especially clear, but the relevant reference would be here: https://github.com/hashicorp/hcl/blob/main/guide/go_expression_eval.rst#expression-evaluation-modes

Adrian
  • 42,911
  • 6
  • 107
  • 99