Skip to content

Instantly share code, notes, and snippets.

@picatz
Created October 7, 2024 22:44
Show Gist options
  • Save picatz/13a2b920bb6ce88f2d03812a713991d0 to your computer and use it in GitHub Desktop.
Save picatz/13a2b920bb6ce88f2d03812a713991d0 to your computer and use it in GitHub Desktop.
HCL v2 Write Custom Traversal
https://github.com/hashicorp/hcl/issues/696
package main
import (
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/hashicorp/hcl/v2/hclwrite"
)
func main() {
file := hclwrite.NewEmptyFile()
body := file.Body()
dataBody := hclwrite.NewEmptyFile().Body()
dataBody.SetAttributeTraversal("config.hcl", hcl.Traversal{
hcl.TraverseRoot{Name: "data"},
hcl.TraverseAttr{Name: "template_file"},
hcl.TraverseAttr{Name: "vault_config"},
hcl.TraverseAttr{Name: "rendered"},
})
dataTokens := dataBody.BuildTokens(nil)
dataAttrTokens := hclwrite.Tokens{
&hclwrite.Token{
Type: hclsyntax.TokenEqual,
Bytes: nil,
},
&hclwrite.Token{
Type: hclsyntax.TokenOBrace,
Bytes: []byte("{\n"),
},
}
dataAttrTokens = append(dataAttrTokens, dataTokens...)
dataAttrTokens = append(dataAttrTokens, &hclwrite.Token{
Type: hclsyntax.TokenCBrace,
Bytes: []byte("}"),
})
body.SetAttributeRaw("data", dataAttrTokens)
hclwrite.Format(file.Bytes())
fmt.Printf("%s", hclwrite.Format(file.Bytes()))
}
data = {
config.hcl = data.template_file.vault_config.rendered
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment