【问题标题】:parse simple terraform file using go使用 go 解析简单的 terraform 文件
【发布时间】:2021-06-02 05:16:45
【问题描述】:

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

我收到了以下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)

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

【问题讨论】:

  • 返回以下诊断信息:&hcl.Diagnostic{Severity:1, Summary:"Missing required argument", Detail:"The argument \"test\" is required, but no definition was found.", Subject:(*hcl.Range)(0xc0000719c0), Context:(*hcl.Range)(nil), Expression:hcl.Expression(nil), EvalContext:(*hcl.EvalContext)(nil)} &hcl.Diagnostic{Severity:1, Summary:"Unsupported block type", Detail:"Blocks of type \"variable\" are not expected here.", Subject:(*hcl.Range)(0xc0000745d0), Context:(*hcl.Range)(nil), Expression:hcl.Expression(nil), EvalContext:(*hcl.EvalContext)(nil)}

标签: go terraform hcl


【解决方案1】:

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

test = "ok"

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

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

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

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

【讨论】:

    【解决方案2】:

    感谢@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"
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 1970-01-01
      • 1970-01-01
      • 2012-04-11
      • 1970-01-01
      相关资源
      最近更新 更多