Using hclwrite to edit attributes in blocks
- Dominant language
- Go
- Stars
- 5.8k
- Forks
- 657
- Avg merge
- 20h 36m
- Merged PRs (30d)
- 6
Description
I am currently trying to change a lot of hcl configs at once. Each config looks something like follows:
```hcl
module "roles-workspace" {
source = "../../../../../../modules/workspace"
org_name = var.org_config.name
vcs_oauth_token_id = var.org_config.vcs_oauth_token_id
read_only_team_ids = var.org_config.read_only_team_ids
write_team_ids = var.org_config.write_team_ids
workspace_cfg_map = {
service_name = "roles"
repo_path = "roles"
repo_branch = "master"
terraform_version = "0.12.2"
workspace_suffix = "roles"
tf_config_root = "ops/terraform/roles"
auto_apply = false
}
}
```
I'm trying to basically mark auto_apply = true and rewrite the config to the same file. HCLWrite is supposedly the best way to achieve this since it preserves any expressions and there's no data loss. However, I can't figure out how to actually get the attribute values within a block and modify it. This is the code I've been playing around with
```go
toBeWritten, _ := hclwrite.ParseConfig(
bytes, path, hcl.InitialPos,
)
for _, block := range toBeWritten.Body().Blocks() {
attr := block.Body().Attributes()["workspace_cfg_map"]
// not sure what to do at this point? How do I get the expression contents? Is there some traversal
that needs to happen here?
traversals := attr.Expr().Variables()
}
```
I've been referencing this issue: https://discuss.hashicorp.com/t/parse-hcl-treating-variables-or-functions-as-raw-strings-hashicorp-hcl/5859
Is there any way to achieve what I'm trying to currently with hclwrite? Or do I have to accept the data loss and use gohcl
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with hclwrite.ParseConfig and the Body, Blocks, Attributes, Expr, and Variables APIs shown in the issue. Determine how an attribute inside workspace_cfg_map can be inspected and changed without losing expressions, then verify that the resulting configuration can be written back to the same file with its existing expressions preserved.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- go
- Domain
- tooling
- Issue type
- Feature
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 30/100