How can I create a tf file from go struct

I want to create a .tf file by executing a Golang script using hashicorp/hcl2.

var "level_1_apis" {
    default = [
             api_name = "service-1-strict-hello",
             endpoint = "/service-1/strict/hello"

I am parsing by this Golang struct.

type Root struct {
	Resources []Resource `hcl:"resource,block"`
	Variables []Variable `hcl:"var,block"`

// Resource ...
type Resource struct {
	Type string `hcl:"type,label"`
	Name string `hcl:"name,label"`

// Variable ...
type Variable struct {
	Type    string         `hcl:"type,label"`
	Default hcl.Expression `hcl:"default"`

I am decoding this by hclparser.ParseHCLFile. I can access to my variables.

How can I do the opposite?

I ran the code below but the output has no default field.

gohcl.EncodeIntoBody(root, rootBody)
	if err := ioutil.WriteFile("./", f.Bytes(), 0644); err != nil {
		return err

var "service-1-3" {

Hi @KeisukeYamashita!

This seems more a HCL question than a Terraform question, but I think I can partially answer it anyway…

The problem here is that gohcl cannot re-encode a hcl.Expression back into source code, because the original source code tokens are lost during parsing/decoding. The gohcl encoder only supports “normal” Go types like string, and struct types with the hcl: tags on their fields.

Terraform’s configuration language uses features that gohcl cannot represent, so to generate Terraform configuration will often require using the lower-level hclwrite API. There is an example called “GenerateFromScratch” in the documentation for that package.