forked from leg100/otf
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathhcl_rewriter.go
More file actions
69 lines (58 loc) · 1.4 KB
/
hcl_rewriter.go
File metadata and controls
69 lines (58 loc) · 1.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package internal
import (
"fmt"
"os"
"path/filepath"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclwrite"
)
type hclOperation func(*hclwrite.File) bool
// RewriteHCL performs HCL surgery on a terraform module.
func RewriteHCL(modulePath string, operations ...hclOperation) error {
return filepath.Walk(modulePath, func(path string, info os.FileInfo, err error) error {
if err != nil {
return nil
}
if modulePath != path && info.IsDir() {
return filepath.SkipDir
}
if filepath.Ext(path) != ".tf" {
return nil
}
cfg, err := os.ReadFile(path)
if err != nil {
return nil
}
f, diags := hclwrite.ParseConfig([]byte(cfg), path, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
return fmt.Errorf("parsing HCL: %s", diags.Error())
}
changed := false
for _, op := range operations {
if op(f) {
changed = true
}
}
if changed {
if err := os.WriteFile(path, f.Bytes(), 0o644); err != nil {
return err
}
}
return nil
})
}
// RemoveBackendBlock is an HCL operation that removes terraform remote backend /
// cloud configuration
func RemoveBackendBlock(f *hclwrite.File) bool {
for _, block := range f.Body().Blocks() {
if block.Type() == "terraform" {
for _, b2 := range block.Body().Blocks() {
if b2.Type() == "backend" || b2.Type() == "cloud" {
block.Body().RemoveBlock(b2)
return true
}
}
}
}
return false
}