forked from jtopjian/ansible-terraform-inventory
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
132 lines (108 loc) · 2.24 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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
)
var (
list = flag.Bool("list", false, "list mode")
)
func main() {
flag.Parse()
if *list {
file := getStatePath()
path, err := filepath.Abs(file)
if err != nil {
errAndExit(fmt.Errorf("Error determining directory: %s", err))
}
f, err := os.Stat(path)
if err != nil {
errAndExit(fmt.Errorf("Error determining directory: %s", err))
}
if !f.IsDir() {
errAndExit(fmt.Errorf("Invalid directory: %s", file))
}
s, err := getState(path)
if err != nil {
errAndExit(err)
}
if s == nil {
fmt.Println("No state was found")
os.Exit(1)
}
j, err := ToJSON(s)
if err != nil {
errAndExit(err)
}
fmt.Println(j)
}
}
func getStatePath() string {
var v string
v = os.Getenv("TF_STATE")
if v != "" {
return v
}
return "."
}
func getState(path string) (State, error) {
var out bytes.Buffer
var state State
terraformVersion := "0.12"
cmd := exec.Command("terraform", "state", "pull")
cmd.Dir = path
cmd.Stdout = &out
err := cmd.Run()
if err != nil {
return nil, fmt.Errorf("Error running `terraform state pull` in directory %s, %s\n", path, err)
}
b, err := ioutil.ReadAll(&out)
if err != nil {
return nil, fmt.Errorf("Error reading output of `terraform state pull`: %s\n", err)
}
// If there was no output, return nil and no error
if string(b) == "" {
return nil, nil
}
if string(b[0]) == "o" && string(b[1]) == ":" {
b = append(b[:0], b[2:]...)
}
var tmpState interface{}
err = json.Unmarshal(b, &tmpState)
if err != nil {
return nil, fmt.Errorf("Error unmarshaling state: %s\n", err)
}
if v, ok := tmpState.(map[string]interface{}); ok {
if v, ok := v["version"].(float64); ok {
if v == 3 {
terraformVersion = "0.11"
}
}
}
switch terraformVersion {
case "0.11":
var s StateV011
err = json.Unmarshal(b, &s)
if err != nil {
return nil, fmt.Errorf("Error unmarshaling state: %s\n", err)
}
state = s
default:
var s StateV012
err = json.Unmarshal(b, &s)
if err != nil {
return nil, fmt.Errorf("Error unmarshaling state: %s\n", err)
}
state = s
}
return state, nil
}
func errAndExit(err error) {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}