使用go解析简单的地形文件

使用go解析简单的地形文件,go,terraform,hcl,Go,Terraform,Hcl,我现在尝试了一切,但无法让这件简单的事情工作 我得到了以下测试文件.hcl: variable "value" { test = "ok" } 我想使用以下代码对其进行解析: package hcl import ( "github.com/hashicorp/hcl/v2/hclsimple" ) type Config struct { Variable string `hcl:"test&quo

我现在尝试了一切,但无法让这件简单的事情工作

我得到了以下
测试文件.hcl

variable "value" {
  test = "ok"
}
我想使用以下代码对其进行解析:

package hcl

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

type Config struct {
    Variable string `hcl:"test"`
}


func HclToStruct(path string) (*Config, error) {
    var config Config

    return &config, hclsimple.DecodeFile(path, nil, &config)
 
但我收到:

test_file.hcl:1,1-1: Missing required argument; The argument "test" is required, but no definition was found., and 1 other diagnostic(s)

我检查了使用相同库的其他项目,但找不到我的错误。。我只是不知道了。有人能告诉我正确的方向吗?

您在这里编写的Go结构类型与您要分析的文件的形状不一致。请注意,输入文件中有一个
变量
块,块内有一个
test
参数,但您编写的Go类型只有
test
参数。因此,HCL解析器希望在顶层找到一个只有
test
参数的文件,如下所示:

test = "ok"
要用
hclsimple
解析这种类似地形的结构,需要编写两种结构类型:一种表示包含
变量的顶级主体,另一种表示每个块的内容。例如:

type Config struct {
  Variables []*Variable `hcl:"variable,block"`
}

type Variable struct {
  Test *string `hcl:"test"`
}

话虽如此,我会注意到Terraform语言使用了HCL的一些特性,
hclsimple
不能支持,或者至少不能支持像这样的直接解码。例如,
variable
块中的
type
参数是一种称为类型约束的特殊表达式,
hclsimple
不直接支持,因此解析它需要使用较低级别的hclapi。(这就是Terraform内部正在做的事情。)

感谢@Martin Atkins,我现在有了以下代码:

type Config struct {
    Variable []Variable `hcl:"variable,block"`
}

type Variable struct {
    Value string `hcl:"name,label"`
    Test string  `hcl:"test"`
}
这样我就可以解析variables.tf了,比如:

variable "projectname" {
  default = "cicd-template"
}

variable "ansibleuser" {
  default = "centos"
} 

返回以下诊断:
&hcl.Diagnostic{严重性:1,摘要:“缺少必需的参数”,详细信息:“参数\“test\”是必需的,但未找到定义。”,主题:(*hcl.Range)(0xc000719c0),上下文:(*hcl.Range)(nil),表达式:hcl.Expression(nil),EvalContext:(*hcl.EvalContext)(nil)}&hcl.Diagnostic{严重性:1,摘要:“不支持的块类型”,详细信息:“此处不需要类型为“变量”的块。”,主题:(*hcl.Range)(0xc0000745d0),上下文:(*hcl.Range)(nil),表达式:hcl.Expression(nil),EvalContext:(*hcl.EvalContext)(nil)}