Skip to content

Commit 7713479

Browse files
committed
allow overwriting the env-var while apply
1 parent cd0fd51 commit 7713479

File tree

17 files changed

+214
-67
lines changed

17 files changed

+214
-67
lines changed

cmd/create.go

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -47,7 +47,11 @@ func Create(dir string, createConfigPath string) {
4747
flog.Infof(":up_arrow: Done Rendering - committing repositories to version control.")
4848

4949
for _, module := range projectConfig.Modules {
50-
vcs.InitializeRepository(module.Files.Repository, module.Parameters["github_access_token"])
50+
err, githubApiKey := module.ReadVendorCredentials("github")
51+
if err != nil {
52+
flog.Errorf(err.Error())
53+
}
54+
vcs.InitializeRepository(module.Files.Repository, githubApiKey)
5155
}
5256
} else {
5357
flog.Infof(":up_arrow: Done Rendering - you will need to commit the created projects to version control.")

internal/apply/apply.go

Lines changed: 18 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,7 @@ import (
1313
"github.com/commitdev/zero/internal/util"
1414
"github.com/hashicorp/terraform/dag"
1515

16+
"github.com/commitdev/zero/internal/config/moduleconfig"
1617
"github.com/commitdev/zero/internal/config/projectconfig"
1718
"github.com/commitdev/zero/pkg/util/exit"
1819
"github.com/commitdev/zero/pkg/util/flog"
@@ -86,14 +87,24 @@ func applyAll(dir string, projectConfig projectconfig.ZeroProjectConfig, applyEn
8687
exit.Fatal("Failed to load module config, credentials cannot be injected properly")
8788
}
8889

89-
envList = util.AppendProjectEnvToCmdEnv(mod.Parameters, envList)
90+
envVarTranslationMap := modConfig.GetParamEnvVarTranslationMap()
91+
envList = util.AppendProjectEnvToCmdEnv(mod.Parameters, envList, envVarTranslationMap)
9092
flog.Debugf("Env injected: %#v", envList)
9193
flog.Infof("Executing apply command for %s...", modConfig.Name)
9294
util.ExecuteCommand(exec.Command("make"), modulePath, envList)
9395
return nil
9496
})
9597
}
9698

99+
func getParameterDefinition(modConfig moduleconfig.ModuleConfig, field string) moduleconfig.Parameter {
100+
for i := 0; i < len(modConfig.Parameters); i++ {
101+
if field == modConfig.Parameters[i].Field {
102+
return modConfig.Parameters[i]
103+
}
104+
}
105+
return moduleconfig.Parameter{}
106+
}
107+
97108
// promptEnvironments Prompts the user for the environments to apply against and returns a slice of strings representing the environments
98109
func promptEnvironments() []string {
99110
items := map[string][]string{
@@ -155,7 +166,12 @@ func summarizeAll(dir string, projectConfig projectconfig.ZeroProjectConfig, app
155166
}
156167
flog.Debugf("Loaded module: %s from %s", name, modulePath)
157168

158-
envList = util.AppendProjectEnvToCmdEnv(mod.Parameters, envList)
169+
modConfig, err := module.ParseModuleConfig(modulePath)
170+
if err != nil {
171+
exit.Fatal("Failed to load module config, credentials cannot be injected properly")
172+
}
173+
envVarTranslationMap := modConfig.GetParamEnvVarTranslationMap()
174+
envList = util.AppendProjectEnvToCmdEnv(mod.Parameters, envList, envVarTranslationMap)
159175
flog.Debugf("Env injected: %#v", envList)
160176
util.ExecuteCommand(exec.Command("make", "summary"), modulePath, envList)
161177
return nil

internal/apply/apply_test.go

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,4 +38,11 @@ func TestApply(t *testing.T) {
3838
assert.NoError(t, err)
3939
assert.Equal(t, "baz: qux\n", string(content))
4040
})
41+
42+
t.Run("Zero apply honors the envVarName overwrite from module definition", func(t *testing.T) {
43+
content, err := ioutil.ReadFile(filepath.Join(tmpDir, "project1/feature.out"))
44+
assert.NoError(t, err)
45+
assert.Equal(t, "envVarName of viaEnvVarName: baz\n", string(content))
46+
})
47+
4148
}

internal/config/moduleconfig/module_config.go

Lines changed: 13 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@ import (
1212
"github.com/commitdev/zero/internal/config/projectconfig"
1313
"github.com/commitdev/zero/pkg/util/flog"
1414
"github.com/iancoleman/strcase"
15-
"github.com/pkg/errors"
1615
)
1716

1817
type ModuleConfig struct {
@@ -38,12 +37,13 @@ type Parameter struct {
3837
Type string `yaml:"type,omitempty"`
3938
OmitFromProjectFile bool `yaml:"omitFromProjectFile,omitempty"`
4039
Conditions []Condition `yaml:"conditions,omitempty"`
40+
EnvVarName string `yaml:"envVarName,omitempty"`
4141
}
4242

4343
type Condition struct {
4444
Action string `yaml:"action"`
4545
MatchField string `yaml:"matchField"`
46-
WhenValue string `yaml:"whenValue,omitempty"`
46+
WhenValue string `yaml:"whenValue"`
4747
Data []string `yaml:"data,omitempty"`
4848
}
4949

@@ -68,6 +68,17 @@ func (cfg ModuleConfig) collectMissing() []string {
6868
return missing
6969
}
7070

71+
func (cfg ModuleConfig) GetParamEnvVarTranslationMap() map[string]string {
72+
translationMap := make(map[string]string)
73+
for i := 0; i < len(cfg.Parameters); i++ {
74+
param := cfg.Parameters[i]
75+
if param.EnvVarName != "" {
76+
translationMap[param.Field] = param.EnvVarName
77+
}
78+
}
79+
return translationMap
80+
}
81+
7182
func LoadModuleConfig(filePath string) (ModuleConfig, error) {
7283
config := ModuleConfig{}
7384

@@ -81,7 +92,6 @@ func LoadModuleConfig(filePath string) (ModuleConfig, error) {
8192
return config, err
8293
}
8394

84-
validateParams(config.Parameters)
8595
missing := config.collectMissing()
8696
if len(missing) > 0 {
8797
flog.Errorf("%v is missing information", filePath)
@@ -96,15 +106,6 @@ func LoadModuleConfig(filePath string) (ModuleConfig, error) {
96106
return config, nil
97107
}
98108

99-
func validateParams(params []Parameter) error {
100-
for _, param := range params {
101-
if param.Type != "" {
102-
return errors.Errorf("type is not supported")
103-
}
104-
}
105-
return nil
106-
}
107-
108109
// Recurses through a datastructure to find any missing data.
109110
// This assumes several things:
110111
// 1. The structure matches that defined by ModuleConfig and its child datastructures.

internal/config/projectconfig/project_config.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
package projectconfig
22

33
import (
4+
"errors"
45
"io/ioutil"
56
"log"
67

@@ -29,6 +30,21 @@ type Module struct {
2930
Conditions []Condition `yaml:"conditions,omitempty"`
3031
}
3132

33+
func (m Module) ReadVendorCredentials(vendor string) (error, string) {
34+
// this mapping could be useful for module config as well
35+
vendorToParamMap := map[string]string{
36+
"github": "githubAccessToken",
37+
"circleci": "circleciApiKey",
38+
}
39+
if parameterKey, ok := vendorToParamMap[vendor]; ok {
40+
if val, ok := m.Parameters[parameterKey]; ok {
41+
return nil, val
42+
}
43+
return errors.New("Parameter not found in module."), ""
44+
}
45+
return errors.New("Unsupported vendor provided."), ""
46+
}
47+
3248
type Parameters map[string]string
3349

3450
type Condition struct {

internal/constants/constants.go

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,12 @@
11
package constants
22

33
const (
4-
TemplatesDir = "tmp/templates"
5-
ZeroProjectYml = "zero-project.yml"
6-
ZeroModuleYml = "zero-module.yml"
7-
UserCredentialsYml = "credentials.yml"
8-
ZeroHomeDirectory = ".zero"
9-
IgnoredPaths = "(?i)zero.module.yml|.git/"
10-
TemplateExtn = ".tmpl"
4+
TemplatesDir = "tmp/templates"
5+
ZeroProjectYml = "zero-project.yml"
6+
ZeroModuleYml = "zero-module.yml"
7+
ZeroHomeDirectory = ".zero"
8+
IgnoredPaths = "(?i)zero.module.yml|.git/"
9+
TemplateExtn = ".tmpl"
1110

1211
// prompt constants
1312

internal/init/custom-prompts.go

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ import (
44
"github.com/commitdev/zero/internal/config/moduleconfig"
55
project "github.com/commitdev/zero/pkg/credentials"
66
"github.com/commitdev/zero/pkg/util/flog"
7-
"github.com/k0kubun/pp"
87
)
98

109
func CustomPromptHandler(promptType string, params map[string]string) {
@@ -31,11 +30,9 @@ func AWSProfilePicker(params map[string]string) {
3130
Validate: NoValidation,
3231
}
3332
_, value := promptParameter(awsPrompt)
34-
pp.Print(value)
3533
credErr := project.FillAWSProfile(value, params)
3634
if credErr != nil {
3735
flog.Errorf("Failed to retrieve profile, falling back to User input")
3836
params["useExistingAwsProfile"] = "no"
3937
}
40-
pp.Print(params)
4138
}

internal/init/init.go

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ func Init(outDir string, localModulePath string) *projectconfig.ZeroProjectConfi
2020
projectConfig := defaultProjConfig()
2121

2222
projectRootParams := map[string]string{}
23+
emptyEnvVarTranslationMap := map[string]string{}
2324
promptName := getProjectNamePrompt()
24-
promptName.RunPrompt(projectRootParams)
25+
promptName.RunPrompt(projectRootParams, emptyEnvVarTranslationMap)
2526
projectConfig.Name = projectRootParams[promptName.Field]
2627

2728
rootDir := path.Join(outDir, projectConfig.Name)
@@ -41,19 +42,19 @@ func Init(outDir string, localModulePath string) *projectconfig.ZeroProjectConfi
4142

4243
initParams := make(map[string]string)
4344
projectConfig.ShouldPushRepositories = true
44-
prompts["ShouldPushRepositories"].RunPrompt(initParams)
45+
prompts["ShouldPushRepositories"].RunPrompt(initParams, emptyEnvVarTranslationMap)
4546
if initParams["ShouldPushRepositories"] == "n" {
4647
projectConfig.ShouldPushRepositories = false
4748
}
4849

4950
// Prompting for push-up stream, then conditionally prompting for github
50-
prompts["GithubRootOrg"].RunPrompt(initParams)
51+
prompts["GithubRootOrg"].RunPrompt(initParams, emptyEnvVarTranslationMap)
5152

5253
projectData := promptAllModules(moduleConfigs)
5354

5455
// Map parameter values back to specific modules
5556
for moduleName, module := range moduleConfigs {
56-
prompts[moduleName].RunPrompt(initParams)
57+
prompts[moduleName].RunPrompt(initParams, emptyEnvVarTranslationMap)
5758
repoName := initParams[prompts[moduleName].Field]
5859
repoURL := fmt.Sprintf("%s/%s", initParams["GithubRootOrg"], repoName)
5960
projectModuleParams := moduleconfig.SummarizeParameters(module, projectData)

internal/init/prompts.go

Lines changed: 12 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ import (
1414
"github.com/commitdev/zero/internal/util"
1515
"github.com/commitdev/zero/pkg/util/exit"
1616
"github.com/commitdev/zero/pkg/util/flog"
17-
"github.com/k0kubun/pp"
1817
"github.com/manifoldco/promptui"
1918
)
2019

@@ -107,7 +106,7 @@ func ValidateProjectName(input string) error {
107106
// 1. Execute (this could potentially be refactored into type + data)
108107
// 2. type: specific ways of obtaining values (in AWS credential case it will set 2 values to the map)
109108
//3.
110-
func (p PromptHandler) RunPrompt(projectParams map[string]string) {
109+
func (p PromptHandler) RunPrompt(projectParams map[string]string, envVarTranslationMap map[string]string) {
111110
var err error
112111
var result string
113112

@@ -120,7 +119,7 @@ func (p PromptHandler) RunPrompt(projectParams map[string]string) {
120119
// so if community module has an `execute: twitter tweet $ENV`
121120
// it wouldnt leak things the module shouldnt have access to
122121
if p.Parameter.Execute != "" {
123-
result = executeCmd(p.Parameter.Execute, projectParams)
122+
result = executeCmd(p.Parameter.Execute, projectParams, envVarTranslationMap)
124123
} else if p.Parameter.Type != "" {
125124
CustomPromptHandler(p.Parameter.Type, projectParams)
126125
} else if p.Parameter.Value != "" {
@@ -172,10 +171,11 @@ func promptParameter(prompt PromptHandler) (error, string) {
172171
return nil, result
173172
}
174173

175-
func executeCmd(command string, envVars map[string]string) string {
176-
pp.Print(envVars)
174+
func executeCmd(command string, envVars map[string]string, envVarTranslationMap map[string]string) string {
177175
cmd := exec.Command("bash", "-c", command)
178-
cmd.Env = util.AppendProjectEnvToCmdEnv(envVars, os.Environ())
176+
// Might need to pass down module's translation map as well,
177+
// currently only works in `zero apply`
178+
cmd.Env = util.AppendProjectEnvToCmdEnv(envVars, os.Environ(), envVarTranslationMap)
179179
out, err := cmd.Output()
180180
flog.Debugf("Running command: %s", command)
181181
if err != nil {
@@ -193,7 +193,7 @@ func sanitizeParameterValue(str string) string {
193193

194194
// PromptParams renders series of prompt UI based on the config
195195
func PromptModuleParams(moduleConfig moduleconfig.ModuleConfig, parameters map[string]string) (map[string]string, error) {
196-
196+
envVarTranslationMap := moduleConfig.GetParamEnvVarTranslationMap()
197197
for _, parameter := range moduleConfig.Parameters {
198198
// deduplicate fields already prompted and received
199199
if _, isAlreadySet := parameters[parameter.Field]; isAlreadySet {
@@ -225,12 +225,9 @@ func PromptModuleParams(moduleConfig moduleconfig.ModuleConfig, parameters map[s
225225
// for k, v := range parameters {
226226
// credentialEnvs[k] = v
227227
// }
228-
promptHandler.RunPrompt(parameters)
229-
230-
// parameters[parameter.Field] = result
231-
pp.Print("Module is done processing %s", moduleConfig.Name)
232-
pp.Print(parameters)
228+
promptHandler.RunPrompt(parameters, envVarTranslationMap)
233229
}
230+
flog.Debugf("Module %s prompt: \n %#v", moduleConfig.Name, parameters)
234231
return parameters, nil
235232
}
236233

@@ -257,8 +254,9 @@ func paramConditionsMapper(conditions []moduleconfig.Condition) CustomConditionS
257254
return func(params map[string]string) bool {
258255
// Prompts must pass every condition to proceed
259256
for i := 0; i < len(conditions); i++ {
260-
if !conditionHandler(conditions[i])(params) {
261-
flog.Debugf("Did not meet condition %v, expected %v to be %v", conditions[i].Action, conditions[i].MatchField, conditions[i].WhenValue)
257+
cond := conditions[i]
258+
if !conditionHandler(cond)(params) {
259+
flog.Debugf("Did not meet condition %v, expected %v to be %v", cond.Action, cond.MatchField, cond.WhenValue)
262260
return false
263261
}
264262
}

0 commit comments

Comments
 (0)