-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathenvironment.go
107 lines (88 loc) · 2.32 KB
/
environment.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
package cli
import (
"errors"
"fmt"
"os"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
const (
deploymentEnvironmentsBaseDir = "terraform/deployments"
deploymentEnvironmentsFoldersBaseDir = "terraform/environments"
)
type environmentConfiguration struct {
Prefix string `json:"prefix"`
Region string `json:"region"`
AWSAccountID string `json:"aws_account_id"`
DDBPrefix string `json:"ddb_prefix"`
StageName string `json:"stage_name"`
}
func fileExists(name string) bool {
if _, err := os.Stat(name); err != nil {
if os.IsNotExist(err) {
return false
}
}
return true
}
func retrieveConfig(cmd *cobra.Command) (*environmentConfiguration, error) {
var tfConfigFileFound bool
p, err := cmd.Flags().GetString("ENV")
if err != nil {
return nil, err
}
if p == "" {
// Try to get prefix from env instead
p = os.Getenv("ENV")
}
env = p
if env == "" {
return nil, errors.New("missing ENV variable")
}
// Check to see if this is running under the git repo root source
if fileExists(fmt.Sprintf(
"%s/%s/config.auto.tfvars.json",
deploymentEnvironmentsBaseDir,
env,
)) {
tfConfigFileFound = true
}
if fileExists(fmt.Sprintf(
"%s/%s/config.auto.tfvars.json",
deploymentEnvironmentsFoldersBaseDir,
env,
)) {
tfConfigFileFound = true
}
v := viper.New()
// If running under the current git repo, use the TF config.auto.tfvars file
// Else use a configuration stored under the $HOME/.rudolph-cli or current working directory
if tfConfigFileFound {
v.SetConfigName("config.auto.tfvars")
v.SetConfigType("json")
v.AddConfigPath(fmt.Sprintf("%s/%s", deploymentEnvironmentsBaseDir, env))
} else {
v.SetConfigName(env)
v.SetConfigType("json")
v.AddConfigPath("$HOME/.rudolph-cli")
v.AddConfigPath(".")
}
if err := v.ReadInConfig(); err != nil {
if _, ok := err.(viper.ConfigFileNotFoundError); ok {
// Config file not found; ignore error if desired
return nil, err
} else {
// Config file was found but another error was produced
return nil, err
}
}
config := &environmentConfiguration{}
err = v.Unmarshal(config)
if err != nil {
return nil, err
}
cmd.Flags().Set("prefix", config.Prefix)
cmd.Flags().Set("region", config.Region)
cmd.Flags().Set("dynamodb_table", fmt.Sprintf("%s_rudolph_store", config.Prefix))
return config, err
}