Hello everyone,
Firstly, sorry if I’m in the wrong category.
I’ve been using the Golang hclwrite library for a few weeks now and was wondering if there was an easier way to handle my use case.
I am not using hclwrite to create terraform files, but to modify them. And I often have the problem that I need to add attributes to an object.
Let’s take the following example:
locals {
an_attribute = {
A = "AAA"
}
another_one = {
"C" = "CCC"
}
and_again = {
an_object = {
a_key = "A Value"
}
}
}
In these three scenarios, I manage to access the attributes with this code:
package main
import (
"fmt"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclwrite"
"log"
"os"
)
func main() {
filePath := "terraform/file.tf"
content, err := os.ReadFile(filePath)
if err != nil {
log.Fatal(err)
return
}
file, diags := hclwrite.ParseConfig(content, filePath, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
log.Fatal(diags.Error())
return
}
body := file.Body()
block := body.FirstMatchingBlock("locals", nil)
an_attribute := block.Body().GetAttribute("an_attribute")
another_one := block.Body().GetAttribute("another_one")
and_again := block.Body().GetAttribute("and_again")
fmt.Println(an_attribute.BuildTokens(nil).WriteTo(os.Stdout))
fmt.Println(another_one.BuildTokens(nil).WriteTo(os.Stdout))
fmt.Println(and_again.BuildTokens(nil).WriteTo(os.Stdout))
}
But if I want to add/modify an attribute to one of my objects, I have to deal with tokens.
Which is tedious. Is there an easier way, or should I continue down this path of pain?
It would be nice to be able to convert the attribute value to capsule type for example.
Thanks in advance!