forked from plumber-cd/terraform-backend-git
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgit_backend_wrappers.go
72 lines (61 loc) · 2.17 KB
/
git_backend_wrappers.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
package main
import (
"log"
"os"
"strings"
"text/template"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/plumber-cd/terraform-backend-git/server"
)
// gitHTTPBackendConfigPath is a path to the backend tf config to generate
const gitHTTPBackendConfigPath = "git_http_backend.auto.tf"
// gitBackendCmd will generate backend config and then start the wrapper
var gitBackendCmd = &cobra.Command{
Use: "git",
Short: "Start backend in Git storage mode and execute the wrapper",
Long: "It will also generate " + gitHTTPBackendConfigPath + " in current working directory pointing to this backend",
PersistentPreRun: func(cmd *cobra.Command, args []string) {
t, err := template.New(gitHTTPBackendConfigPath).Parse(`
terraform {
backend "http" {
address = "http://localhost:{{ .port }}/?type=git&repository={{ .repository }}&ref={{ .ref }}&state={{ .state }}"
lock_address = "http://localhost:{{ .port }}/?type=git&repository={{ .repository }}&ref={{ .ref }}&state={{ .state }}"
unlock_address = "http://localhost:{{ .port }}/?type=git&repository={{ .repository }}&ref={{ .ref }}&state={{ .state }}"
username = "{{ .username }}"
password = "{{ .password }}"
}
}
`)
if err != nil {
log.Fatal(err)
}
username, _ := os.LookupEnv("TF_BACKEND_GIT_HTTP_USERNAME")
password, _ := os.LookupEnv("TF_BACKEND_GIT_HTTP_PASSWORD")
addr := strings.Split(viper.GetString("address"), ":")
p := map[string]string{
"port": addr[len(addr)-1],
"username": username,
"password": password,
}
for _, flag := range []string{"repository", "ref", "state"} {
if p[flag] = viper.GetString("git." + flag); p[flag] == "" {
log.Fatalf("%s must be set", flag)
}
}
backendConfig, err := os.OpenFile(gitHTTPBackendConfigPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
if err != nil {
log.Fatal(err)
}
defer backendConfig.Close()
if err := t.Execute(backendConfig, p); err != nil {
log.Fatal(err)
}
go server.Start()
},
PersistentPostRun: func(cmd *cobra.Command, args []string) {
if err := os.Remove(gitHTTPBackendConfigPath); err != nil {
log.Fatal(err)
}
},
}