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?

1
  • As you see from the answer, this is impossible in plain HCL. Actually, the inability to do variable substitutions in the same file led me to creating my own, HCL-like format, BCL: github.com/wkhere/bcl . It is now undergoing a major rewrite to arrive with a new parser, nested blocks with cross-references and some handy builtins. If you like some aspect of it, please stay tuned. Commented Oct 21, 2023 at 14:26

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.