Skip to content

Instantly share code, notes, and snippets.

@SeanHood
Created March 31, 2022 12:01
Show Gist options
  • Save SeanHood/408bc4dfc6a21aac7ec2d7ea5a97ce10 to your computer and use it in GitHub Desktop.
Save SeanHood/408bc4dfc6a21aac7ec2d7ea5a97ce10 to your computer and use it in GitHub Desktop.
Read/Update/Write HCL2 with Go + hclwrite
package main
import (
"fmt"
"io/ioutil"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclwrite"
"github.com/zclconf/go-cty/cty"
)
func main() {
filename := "tf/main.tf"
tfFile, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Println(err)
}
f, diags := hclwrite.ParseConfig(tfFile, "debug.tf", hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
panic(fmt.Errorf("config parse: %w", diags))
}
rootBody := f.Body().Blocks()
// Example file only has 1 resource
// Should probably do something to find the resource we care about
modBody := rootBody[0].Body()
modBody.SetAttributeValue("terraform_version", cty.StringVal("0.13.7"))
fmt.Printf("%s", f.Bytes())
ioutil.WriteFile(filename, f.Bytes(), 0600)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment