forked from im2nguyen/rover
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
324 lines (270 loc) · 8.08 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
package main
import (
"context"
"embed"
"encoding/json"
"errors"
"flag"
"fmt"
"io/fs"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"strings"
"time"
"github.com/hashicorp/terraform-config-inspect/tfconfig"
"github.com/hashicorp/terraform-exec/tfexec"
tfjson "github.com/hashicorp/terraform-json"
)
const VERSION = "0.2.1"
//go:embed ui/dist
var frontend embed.FS
type arrayFlags []string
func (i arrayFlags) String() string {
var ts []string
for _, el := range i {
ts = append(ts, el)
}
return strings.Join(ts, ",")
}
func (i *arrayFlags) Set(value string) error {
*i = append(*i, value)
return nil
}
type rover struct {
Name string
WorkingDir string
TfPath string
TfVarsFiles []string
TfVars []string
TfBackendConfigs []string
PlanPath string
WorkspaceName string
TFConfigExists bool
ShowSensitive bool
Config *tfconfig.Module
Plan *tfjson.Plan
RSO *ResourcesOverview
Map *Map
Graph Graph
}
func main() {
var tfPath, workingDir, name, zipFileName, ipPort, planPath, workspaceName string
var standalone, tfConfigExists, showSensitive, getVersion bool
var tfVarsFiles, tfVars, tfBackendConfigs arrayFlags
flag.StringVar(&tfPath, "tfPath", "/usr/local/bin/terraform", "Path to Terraform binary")
flag.StringVar(&workingDir, "workingDir", ".", "Path to Terraform configuration")
flag.StringVar(&name, "name", "rover", "Configuration name")
flag.StringVar(&zipFileName, "zipFileName", "rover", "Standalone zip file name")
flag.StringVar(&ipPort, "ipPort", "0.0.0.0:9000", "IP and port for Rover server")
flag.StringVar(&planPath, "planPath", "", "Plan file path")
flag.StringVar(&workspaceName, "workspaceName", "", "Workspace name")
flag.BoolVar(&standalone, "standalone", false, "Generate standalone HTML files")
flag.BoolVar(&tfConfigExists, "tfConfigExists", true, "Terraform configuration exist - set to false if Terraform configuration unavailable (Terraform Cloud, Terragrunt, auto-generated HCL, CDKTF)")
flag.BoolVar(&showSensitive, "showSensitive", false, "Display sensitive values")
flag.BoolVar(&getVersion, "version", false, "Get current version")
flag.Var(&tfVarsFiles, "tfVarsFile", "Path to *.tfvars files")
flag.Var(&tfVars, "tfVar", "Terraform variable (key=value)")
flag.Var(&tfBackendConfigs, "tfBackendConfig", "Path to *.tfbackend files")
flag.Parse()
if getVersion {
fmt.Printf("Rover v%s\n", VERSION)
return
}
log.Println("Starting Rover...")
parsedTfVarsFiles := strings.Split(tfVarsFiles.String(), ",")
parsedTfVars := strings.Split(tfVars.String(), ",")
parsedTfBackendConfigs := strings.Split(tfBackendConfigs.String(), ",")
if planPath != "" {
path, err := os.Getwd()
if err != nil {
log.Fatal(errors.New("Unable to get current working directory"))
}
if !strings.HasPrefix(planPath, "/") {
planPath = filepath.Join(path, planPath)
}
}
r := rover{
Name: name,
WorkingDir: workingDir,
TfPath: tfPath,
PlanPath: planPath,
TFConfigExists: tfConfigExists,
ShowSensitive: showSensitive,
TfVarsFiles: parsedTfVarsFiles,
TfVars: parsedTfVars,
TfBackendConfigs: parsedTfBackendConfigs,
WorkspaceName: workspaceName,
}
// Generate assets
err := r.generateAssets()
if err != nil {
log.Fatal(err.Error())
}
log.Println("Done generating assets.")
// Save to file (debug)
// saveJSONToFile(name, "plan", "output", r.Plan)
// saveJSONToFile(name, "rso", "output", r.Plan)
// saveJSONToFile(name, "map", "output", r.Map)
// saveJSONToFile(name, "graph", "output", r.Graph)
// Embed frontend
fe, err := fs.Sub(frontend, "ui/dist")
if err != nil {
log.Fatalln(err)
}
frontendFS := http.FileServer(http.FS(fe))
if standalone {
err = r.generateZip(fe, fmt.Sprintf("%s.zip", zipFileName))
if err != nil {
log.Fatalln(err)
}
log.Printf("Generated zip file: %s.zip\n", zipFileName)
return
}
err = r.startServer(ipPort, frontendFS)
if err != nil {
log.Fatalf("Could not start server: %s\n", err.Error())
}
}
func (r *rover) generateAssets() error {
// Get Plan
err := r.getPlan()
if err != nil {
return errors.New(fmt.Sprintf("Unable to parse Plan: %s", err))
}
if r.TFConfigExists {
// Parse Configuration
log.Println("Parsing configuration...")
// Get current directory file
r.Config, _ = tfconfig.LoadModule(r.WorkingDir)
if r.Config.Diagnostics.HasErrors() {
return errors.New(fmt.Sprintf("Unable to parse configuration: %s", r.Config.Diagnostics.Error()))
}
}
// Generate RSO, Map, Graph
err = r.GenerateResourceOverview()
if err != nil {
return err
}
err = r.GenerateMap()
if err != nil {
return err
}
err = r.GenerateGraph()
if err != nil {
return err
}
return nil
}
func (r *rover) getPlan() error {
tmpDir, err := ioutil.TempDir("", "rover")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
tf, err := tfexec.NewTerraform(r.WorkingDir, r.TfPath)
if err != nil {
return err
}
// If user provided path to plan file
if r.PlanPath != "" {
log.Println("Using provided plan...")
r.Plan, err = tf.ShowPlanFile(context.Background(), r.PlanPath)
if err != nil {
return errors.New(fmt.Sprintf("Unable to read Plan (%s): %s", r.PlanPath, err))
}
return nil
}
log.Println("Initializing Terraform...")
// Create TF Init options
var tfInitOptions []tfexec.InitOption
tfInitOptions = append(tfInitOptions, tfexec.Upgrade(true))
// Add *.tfbackend files
for _, tfBackendConfig := range r.TfBackendConfigs {
if tfBackendConfig != "" {
tfInitOptions = append(tfInitOptions, tfexec.BackendConfig(tfBackendConfig))
}
}
// tfInitOptions = append(tfInitOptions, tfexec.LockTimeout("60s"))
err = tf.Init(context.Background(), tfInitOptions...)
if err != nil {
return errors.New(fmt.Sprintf("Unable to initialize Terraform Plan: %s", err))
}
if r.WorkspaceName != "" {
log.Printf("Running in %s workspace...", r.WorkspaceName)
err = tf.WorkspaceSelect(context.Background(), r.WorkspaceName)
if err != nil {
return errors.New(fmt.Sprintf("Unable to select workspace (%s): %s", r.WorkspaceName, err))
}
}
log.Println("Generating plan...")
planPath := fmt.Sprintf("%s/%s-%v", tmpDir, "roverplan", time.Now().Unix())
// Create TF Plan options
var tfPlanOptions []tfexec.PlanOption
tfPlanOptions = append(tfPlanOptions, tfexec.Out(planPath))
// Add *.tfvars files
for _, tfVarsFile := range r.TfVarsFiles {
if tfVarsFile != "" {
tfPlanOptions = append(tfPlanOptions, tfexec.VarFile(tfVarsFile))
}
}
// Add Terraform variables
for _, tfVar := range r.TfVars {
if tfVar != "" {
tfPlanOptions = append(tfPlanOptions, tfexec.Var(tfVar))
}
}
_, err = tf.Plan(context.Background(), tfPlanOptions...)
if err != nil {
return errors.New(fmt.Sprintf("Unable to run Plan: %s", err))
}
r.Plan, err = tf.ShowPlanFile(context.Background(), planPath)
if err != nil {
return errors.New(fmt.Sprintf("Unable to read Plan: %s", err))
}
return nil
}
func showJSON(g interface{}) {
j, err := json.Marshal(g)
if err != nil {
log.Printf("Error producing JSON: %s\n", err)
os.Exit(2)
}
log.Printf("%+v", string(j))
}
func showModuleJSON(module *tfconfig.Module) {
j, err := json.MarshalIndent(module, "", " ")
if err != nil {
fmt.Fprintf(os.Stderr, "error producing JSON: %s\n", err)
os.Exit(2)
}
os.Stdout.Write(j)
os.Stdout.Write([]byte{'\n'})
}
func saveJSONToFile(prefix string, fileType string, path string, j interface{}) string {
b, err := json.Marshal(j)
if err != nil {
fmt.Fprintf(os.Stderr, "error producing JSON: %s\n", err)
os.Exit(2)
}
newpath := filepath.Join(".", fmt.Sprintf("%s/%s", path, prefix))
err = os.MkdirAll(newpath, os.ModePerm)
if err != nil {
log.Fatal(err)
}
f, err := os.Create(fmt.Sprintf("%s/%s-%s.json", newpath, prefix, fileType))
if err != nil {
log.Fatal(err)
}
defer f.Close()
_, err = f.WriteString(string(b))
if err != nil {
log.Fatal(err)
}
return fmt.Sprintf("%s/%s-%s.json", newpath, prefix, fileType)
}
func enableCors(w *http.ResponseWriter) {
(*w).Header().Set("Access-Control-Allow-Origin", "*")
}