首页 > 解决方案 > 使用 go 解析简单的 terraform 文件

问题描述

我现在尝试了一切,但无法让这个简单的事情发挥作用。

我得到以下信息test_file.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)

我检查了使用同一个库的其他项目,但我找不到我的错误..我只是不知道了。有人可以引导我走向正确的方向吗?

标签: goterraformhcl

解决方案


您在此处编写的 Go 结构类型与您要解析的文件的形状不对应。请注意,输入文件有一个variable带有test参数的块,但您编写的 Go 类型只有test参数。出于这个原因,HCL 解析器期望找到一个只有test顶层参数的文件,如下所示:

test = "ok"

要解析这种类似 Terraform 的结构,hclsimple您需要编写两种结构类型:一种表示包含块的顶层主体variable,另一种表示每个块的内容。例如:

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

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

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


推荐阅读