forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terraform.go
92 lines (80 loc) · 1.99 KB
/
terraform.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
package terraform
import (
"fmt"
"github.com/jenkins-x/jx/pkg/util"
"io/ioutil"
"os"
"strings"
)
func Init(terraformDir string, serviceAccountPath string) error {
os.Setenv("GOOGLE_CREDENTIALS", serviceAccountPath)
err := util.RunCommand("", "terraform", "init", terraformDir)
if err != nil {
return err
}
return nil
}
func Plan(terraformDir string, terraformVars string, serviceAccountPath string) error {
err := util.RunCommand("", "terraform", "plan",
fmt.Sprintf("-var-file=%s", terraformVars),
"-var",
fmt.Sprintf("credentials=%s", serviceAccountPath),
terraformDir)
if err != nil {
return err
}
return nil
}
func Apply(terraformDir string, terraformVars string, serviceAccountPath string) error {
err := util.RunCommand("", "terraform", "apply", "-auto-approve",
fmt.Sprintf("-var-file=%s", terraformVars),
"-var",
fmt.Sprintf("credentials=%s", serviceAccountPath),
terraformDir)
if err != nil {
return err
}
return nil
}
func WriteKeyValueToFileIfNotExists(path string, key string, value string) error {
// file exists
if _, err := os.Stat(path); err == nil {
buffer, err := ioutil.ReadFile(path)
if err != nil {
return err
}
contents := string(buffer)
if strings.Contains(contents, key) {
return nil
}
}
file, err := os.OpenFile(path, os.O_WRONLY|os.O_APPEND|os.O_CREATE, 0644)
if err != nil {
return err
}
defer file.Close()
line := fmt.Sprintf("%s = \"%s\"\n", key, value)
_, err = file.WriteString(line)
if err != nil {
return err
}
return nil
}
func ReadValueFromFile(path string, key string) (string, error) {
if _, err := os.Stat(path); err == nil {
buffer, err := ioutil.ReadFile(path)
if err != nil {
return "", err
}
contents := string(buffer)
lines := strings.Split(contents, "\n")
for _, line := range lines {
if strings.Contains(line, key) {
tokens := strings.Split(line, "=")
trimmedValue := strings.Trim(strings.TrimSpace(tokens[1]), "\"")
return trimmedValue, nil
}
}
}
return "", nil
}