如何使用gohcl.DecodeBody解析含sensitive变量的Terraform脚本
解决gohcl.DecodeBody解析Terraform脚本时sensitive属性报错的问题
当使用gohcl.DecodeBody解析包含sensitive属性的Terraform变量文件时,不传EvalContext或传空上下文会触发"Unsupported argument"错误,原因是默认解码器不识别Terraform的sensitive参数。以下是两种可行的解决方式:
方式一:构造支持Terraform变量块的EvalContext
通过注册Terraform变量块的标准schema,让解码器识别sensitive属性。需要导入terraform-config-inspect库获取官方定义的变量块schema:
import ( "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/gohcl" "github.com/hashicorp/terraform-config-inspect/tfconfig" ) // 构造包含变量块schema的EvalContext ctx := &hcl.EvalContext{} gohcl.RegisterDecoder(ctx, tfconfig.VariableBlockSchema) // 传入上下文解析文件 diags := gohcl.DecodeBody(file.Body, ctx, &root) if diags.HasErrors() { // 处理诊断错误 }
方式二:忽略所有未知属性
如果不需要读取sensitive的值,仅需跳过该属性,可以通过自定义schema并开启AllowUnknownAttributes实现:
import ( "github.com/hashicorp/hcl/v2" "github.com/hashicorp/hcl/v2/gohcl" ) // 定义你的结构体(示例为变量块结构) type Root struct { Variables []Variable `hcl:"variable,block"` } type Variable struct { Name string `hcl:"name,label"` Description string `hcl:"description,optional"` Type hcl.Type `hcl:"type,optional"` Default hcl.Expression `hcl:"default,optional"` } // 生成结构体对应的schema,并允许未知属性 schema, err := gohcl.ImpliedSchema(Root{}) if err != nil { panic(err) } // 针对variable块开启未知属性允许 schema.Blocks["variable"].AllowUnknownAttributes = true // 使用带schema的方式解析 diags := hcl.DecodeBody(file.Body, nil, &root, hcl.Schema(schema)) if diags.HasErrors() { // 处理诊断错误 }
内容的提问来源于stack exchange,提问作者GabeV
相关产品推荐
相关产品推荐

