/
plan.go
126 lines (103 loc) · 2.63 KB
/
plan.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
package libs
import (
"context"
"github.com/hashicorp/go-version"
"github.com/hashicorp/hc-install/product"
tfreleases "github.com/hashicorp/hc-install/releases"
"github.com/hashicorp/terraform-exec/tfexec"
"io/ioutil"
"os"
)
const (
EnvKeySumoAccessID = "SUMOLOGIC_ACCESSID"
EnvKeySumoAccessKey = "SUMOLOGIC_ACCESSKEY"
EnvKeySumoEnvironment = "SUMOLOGIC_ENVIRONMENT"
EnvKeyHTTPProxy = "HTTP_PROXY"
EnvKeyHTTPSProxy = "HTTPS_PROXY"
)
type TFAction string
const (
TFPlan TFAction = "PLAN"
TFApply TFAction = "APPLY"
TFPlanDestroy TFAction = "PlanDestroy"
TFDestroy TFAction = "DESTROY"
)
func TFExec(wdPath string, action TFAction) error {
tmpDir, err := ioutil.TempDir("", "tfinstall")
if err != nil {
log.Errorf("error creating temp dir: %s", err)
return err
}
defer os.RemoveAll(tmpDir)
installer := &tfreleases.ExactVersion{
Product: product.Terraform,
Version: version.Must(version.NewVersion("1.2.2")),
InstallDir: tmpDir,
}
execPath, err := installer.Install(context.Background())
if err != nil {
log.Errorf("error locating Terraform binary: %s", err)
return err
}
tf, err := tfexec.NewTerraform(wdPath, execPath)
env := map[string]string{
EnvKeyHTTPProxy: os.Getenv(EnvKeyHTTPProxy),
EnvKeyHTTPSProxy: os.Getenv(EnvKeyHTTPSProxy),
EnvKeySumoAccessID: os.Getenv(EnvKeySumoAccessID),
EnvKeySumoAccessKey: os.Getenv(EnvKeySumoAccessKey),
EnvKeySumoEnvironment: os.Getenv(EnvKeySumoEnvironment),
}
err = tf.SetEnv(env)
if err != nil {
log.Error(err)
return err
}
err = tf.Init(context.Background(), tfexec.Upgrade(true))
if err != nil {
log.Errorf("error running Init: %s", err)
return err
}
// _, err = tf.Show(context.Background())
// if err != nil {
// log.Errorf("error running Show: %s", err)
// return err
// }
tf.SetStdout(os.Stdout)
tf.SetLogger(InfoLogger{})
tf.SetStderr(os.Stderr)
if err != nil {
log.Errorf("error running NewTerraform: %s", err)
return err
}
var ok bool
if action == TFPlan {
ok, err = tf.Plan(context.Background())
if !ok && err == nil {
log.Info("no changes found in tf plan")
}
}
if action == TFApply {
err = tf.Apply(context.Background())
if err != nil {
log.Error(err)
return err
}
}
if action == TFPlanDestroy {
WarnUInfo("\nresource that will be destroyed\n\n")
ok, err = tf.Plan(context.Background(), tfexec.Destroy(true))
if err != nil {
log.Error(err)
return err
}
}
if action == TFDestroy {
err = tf.Destroy(context.Background())
if err != nil {
log.Error(err)
return err
}
}
return nil
}
const LookupTableIdKey = "lookupTableId"