forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
terraform.go
111 lines (98 loc) · 2.36 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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
package terraform
import (
"fmt"
"io/ioutil"
"os"
"strings"
"github.com/jenkins-x/jx/pkg/util"
"io"
)
func Init(terraformDir string, serviceAccountPath string) error {
fmt.Println("Initialising Terraform")
os.Setenv("GOOGLE_CREDENTIALS", serviceAccountPath)
cmd := util.Command{
Name: "terraform",
Args: []string{"init", terraformDir},
}
_, err := cmd.RunWithoutRetry()
if err != nil {
return err
}
return nil
}
func Plan(terraformDir string, terraformVars string, serviceAccountPath string) (string, error) {
fmt.Println("Showing Terraform Plan")
cmd := util.Command{
Name: "terraform",
Args: []string{"plan",
fmt.Sprintf("-var-file=%s", terraformVars),
"-var",
fmt.Sprintf("credentials=%s", serviceAccountPath),
terraformDir},
}
out, err := cmd.RunWithoutRetry()
if err != nil {
return out, err
}
return out, nil
}
func Apply(terraformDir string, terraformVars string, serviceAccountPath string, stdout io.Writer, stderr io.Writer) error {
fmt.Println("Applying Terraform")
cmd := util.Command{
Name: "terraform",
Args: []string{"apply", "-auto-approve",
fmt.Sprintf("-var-file=%s", terraformVars),
"-var",
fmt.Sprintf("credentials=%s", serviceAccountPath),
terraformDir},
Out: stdout,
Err: stderr,
}
_, err := cmd.RunWithoutRetry()
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
}