-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
68 lines (58 loc) · 1.54 KB
/
main.go
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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
ctyjson "github.com/zclconf/go-cty/cty/json"
)
func main() {
args := os.Args[1:]
if len(args) != 1 {
fmt.Fprintf(os.Stderr, "Usage: tfvars-json file.tfvars\n")
os.Exit(1)
}
filename := args[0]
src, err := ioutil.ReadFile(filename)
if err != nil {
fmt.Fprintf(os.Stderr, "Error reading %q: %s", filename, err)
os.Exit(1)
}
f, diags := hclsyntax.ParseConfig(src, filename, hcl.Pos{Line: 1, Column: 1})
if diags.HasErrors() {
fmt.Fprintf(os.Stderr, "Error parsing %q: %s", filename, diags.Error())
os.Exit(1)
}
if f.Body == nil {
fmt.Println("{}")
os.Exit(0)
}
attrs, diags := f.Body.JustAttributes()
if diags.HasErrors() {
fmt.Fprintf(os.Stderr, "Error evaluating %q: %s", filename, diags.Error())
os.Exit(1)
}
values := make(map[string]json.RawMessage, len(attrs))
for name, attr := range attrs {
value, diags := attr.Expr.Value(nil)
if diags.HasErrors() {
fmt.Fprintf(os.Stderr, "Error evaluating %q in %q: %s", name, filename, diags.Error())
os.Exit(1)
}
buf, err := ctyjson.Marshal(value, value.Type())
if err != nil {
fmt.Fprintf(os.Stderr, "Error converting %q in %q to JSON: %s", name, filename, err)
os.Exit(1)
}
values[name] = json.RawMessage(buf)
}
output, err := json.MarshalIndent(values, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "Error marshalling %q to JSON: %s", filename, err)
os.Exit(1)
}
fmt.Println(string(output))
os.Exit(0)
}