hashicorp / hashicorp/hcl

hclwrite: SetAttributeRaw() after Clear() is not present in hcl.Bytes() output

Open
#623 0 comments 0 reactions 0 assignees View on GitHub
Dominant language
Go
Stars
5.8k
Forks
657
Avg merge
20h 36m
Merged PRs (30d)
6

Description

I'm writing some code to take in an HCL file (Packer in this case) and perform some transformations on it (it's a shame the JSON is deprecated as this was an easier format to parse, but that's another thing).

I'm not sure if it's something I'm not doing right or if this is perhaps a bug?

I get the attributes `attrs := build.Body().Attributes()` (`build` is a Block within the HCL file) and then clear the build (`build.Body().Clear()`) element for injecting the extra blocks I need.

Obviously to get it back to the same state I need to now re-set the Attributes and munged Blocks onto the `build` Block.

I do this with the following (for Attributes):
```go
for attrName, attrValue := range attrs {
build.Body().SetAttributeRaw(attrName, attrValue.Expr().BuildTokens(hclwrite.Tokens{}))
build.Body().AppendNewline()
}
```

I can then get the new Attributes print the result of the `Attributes` method and see the correct output:
```go
attrs = build.Body().Attributes()
for attrName, attrValue := range attrs {
fmt.Printf("%s = %s", attrName, attrValue.Expr().BuildTokens(hclwrite.Tokens{}).Bytes())
}
```
Output: `sources = ["source.azure-arm.build_vhd"]`

This successfully prints Attributes, however when I go to then write the file back out, the Attributes are missing:
```go
os.WriteFile("output.hcl", hcl.Bytes(), 0644)
```

Expecting:
![image](https://github.com/hashicorp/hcl/assets/2286713/4da83ba0-f1d6-4776-bdfb-f5d89d88791e)

Received:
![image](https://github.com/hashicorp/hcl/assets/2286713/855eb8e0-592c-4ecd-a25b-112ce7eb7f29)

It seems somehow by setting Attributes there on the Body element but don't get considered when written back out to a file.

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.