HCL文件中的变量无法解析。

huangapple go评论89阅读模式
英文:

Variables in the HCL file cannot be parsed

问题

我有一个 Go 项目,我想读取一个 HCL 文件。这个 HCL 文件包含变量。然而,我无法解析它,我得到了以下错误信息:

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

我的 Go 代码:

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)
}

我的 HCL 文件:

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

我做错了什么?我的 HCL 语法可能不正确吗?

英文:

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

得分: 3

我的HCL语法可能不正确吗?

它在语法上是有效的,但它不会按照你的期望工作。HCL不允许引用在HCL文件中定义的任意值,它只允许引用由解析器公开的变量。例如,以下代码将给出预期的输出:

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

文档并没有特别清楚地说明这一点,但相关的参考资料可以在这里找到:https://github.com/hashicorp/hcl/blob/main/guide/go_expression_eval.rst#expression-evaluation-modes

英文:

> 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

huangapple
  • 本文由 发表于 2022年9月16日 20:23:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/73744779.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定