-
Notifications
You must be signed in to change notification settings - Fork 52
/
init.go
352 lines (311 loc) · 10.4 KB
/
init.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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
package init
import (
"fmt"
"os"
"path"
"sync"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/awserr"
"github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/sts"
"github.com/commitdev/zero/internal/config/globalconfig"
"github.com/commitdev/zero/internal/config/moduleconfig"
"github.com/commitdev/zero/internal/config/projectconfig"
"github.com/commitdev/zero/internal/module"
"github.com/commitdev/zero/internal/registry"
project "github.com/commitdev/zero/pkg/credentials"
"github.com/commitdev/zero/pkg/util/exit"
"github.com/commitdev/zero/pkg/util/flog"
"github.com/manifoldco/promptui"
)
// Create cloud provider context
func Init(outDir string) *projectconfig.ZeroProjectConfig {
projectConfig := defaultProjConfig()
projectConfig.Name = getProjectNamePrompt().GetParam(projectConfig.Parameters)
rootDir := path.Join(outDir, projectConfig.Name)
flog.Infof(":tada: Initializing project")
err := os.MkdirAll(rootDir, os.ModePerm)
if os.IsExist(err) {
exit.Fatal("Directory %v already exists! Error: %v", projectConfig.Name, err)
} else if err != nil {
exit.Fatal("Error creating root: %v ", err)
}
moduleSources := chooseStack(registry.GetRegistry())
moduleConfigs, mappedSources := loadAllModules(moduleSources)
prompts := getProjectPrompts(projectConfig.Name, moduleConfigs)
initParams := make(map[string]string)
projectConfig.ShouldPushRepositories = true
initParams["ShouldPushRepositories"] = prompts["ShouldPushRepositories"].GetParam(initParams)
if initParams["ShouldPushRepositories"] == "n" {
projectConfig.ShouldPushRepositories = false
}
// Prompting for push-up stream, then conditionally prompting for github
initParams["GithubRootOrg"] = prompts["GithubRootOrg"].GetParam(initParams)
projectCredentials := globalconfig.GetProjectCredentials(projectConfig.Name)
credentialPrompts := getCredentialPrompts(projectCredentials, moduleConfigs)
projectCredentials = promptCredentialsAndFillProjectCreds(credentialPrompts, projectCredentials)
globalconfig.Save(projectCredentials)
projectParameters := promptAllModules(moduleConfigs)
// Map parameter values back to specific modules
for moduleName, module := range moduleConfigs {
repoName := prompts[moduleName].GetParam(initParams)
repoURL := fmt.Sprintf("%s/%s", initParams["GithubRootOrg"], repoName)
projectModuleParams := make(projectconfig.Parameters)
// Loop through all the prompted values and find the ones relevant to this module
for parameterKey, parameterValue := range projectParameters {
for _, moduleParameter := range module.Parameters {
if moduleParameter.Field == parameterKey {
projectModuleParams[parameterKey] = parameterValue
}
}
}
projectConfig.Modules[moduleName] = projectconfig.NewModule(projectModuleParams, repoName, repoURL, mappedSources[moduleName])
}
// TODO: load ~/.zero/config.yml (or credentials)
// TODO: prompt global credentials
return &projectConfig
}
// loadAllModules takes a list of module sources, downloads those modules, and parses their config
func loadAllModules(moduleSources []string) (map[string]moduleconfig.ModuleConfig, map[string]string) {
modules := make(map[string]moduleconfig.ModuleConfig)
mappedSources := make(map[string]string)
wg := sync.WaitGroup{}
wg.Add(len(moduleSources))
for _, moduleSource := range moduleSources {
go module.FetchModule(moduleSource, &wg)
}
wg.Wait()
for _, moduleSource := range moduleSources {
mod, err := module.ParseModuleConfig(moduleSource)
if err != nil {
exit.Fatal("Unable to load module: %v\n", err)
}
modules[mod.Name] = mod
mappedSources[mod.Name] = moduleSource
}
return modules, mappedSources
}
// promptAllModules takes a map of all the modules and prompts the user for values for all the parameters
func promptAllModules(modules map[string]moduleconfig.ModuleConfig) map[string]string {
parameterValues := make(map[string]string)
for _, config := range modules {
var err error
parameterValues, err = PromptModuleParams(config, parameterValues)
if err != nil {
exit.Fatal("Exiting prompt: %v\n", err)
}
}
return parameterValues
}
// Project name is prompt individually because the rest of the prompts
// requires the projectName to populate defaults
func getProjectNamePrompt() PromptHandler {
return PromptHandler{
moduleconfig.Parameter{
Field: "projectName",
Label: "Project Name",
Default: "",
},
NoCondition,
NoValidation,
}
}
func getProjectPrompts(projectName string, modules map[string]moduleconfig.ModuleConfig) map[string]PromptHandler {
handlers := map[string]PromptHandler{
"ShouldPushRepositories": {
moduleconfig.Parameter{
Field: "ShouldPushRepositories",
Label: "Should the created projects be checked into github automatically? (y/n)",
Default: "y",
},
NoCondition,
SpecificValueValidation("y", "n"),
},
"GithubRootOrg": {
moduleconfig.Parameter{
Field: "GithubRootOrg",
Label: "What's the root of the github org to create repositories in?",
Default: "github.com/",
},
KeyMatchCondition("ShouldPushRepositories", "y"),
NoValidation,
},
}
for moduleName, module := range modules {
label := fmt.Sprintf("What do you want to call the %s project?", moduleName)
handlers[moduleName] = PromptHandler{
moduleconfig.Parameter{
Field: moduleName,
Label: label,
Default: module.OutputDir,
},
NoCondition,
NoValidation,
}
}
return handlers
}
func getCredentialPrompts(projectCredentials globalconfig.ProjectCredential, moduleConfigs map[string]moduleconfig.ModuleConfig) []CredentialPrompts {
var uniqueVendors []string
for _, module := range moduleConfigs {
uniqueVendors = appendToSet(uniqueVendors, module.RequiredCredentials)
}
// map is to keep track of which vendor they belong to, to fill them back into the projectConfig
prompts := []CredentialPrompts{}
for _, vendor := range AvailableVendorOrders {
if itemInSlice(uniqueVendors, vendor) {
vendorPrompts := CredentialPrompts{vendor, mapVendorToPrompts(projectCredentials, vendor)}
prompts = append(prompts, vendorPrompts)
}
}
return prompts
}
func mapVendorToPrompts(projectCred globalconfig.ProjectCredential, vendor string) []PromptHandler {
var prompts []PromptHandler
profiles, err := project.GetAWSProfiles()
if err != nil {
profiles = []string{}
}
// if no profiles available, dont prompt use to pick profile
customAwsPickProfileCondition := func(param map[string]string) bool {
if len(profiles) == 0 {
flog.Infof(":warning: No AWS profiles found, please manually input AWS credentials")
return false
} else {
return true
}
}
// condition for prompting manual AWS credentials input
customAwsMustInputCondition := func(param map[string]string) bool {
toPickProfile := awsPickProfile
if val, ok := param["use_aws_profile"]; ok && val != toPickProfile {
return true
}
return false
}
switch vendor {
case "aws":
awsPrompts := []PromptHandler{
{
moduleconfig.Parameter{
Field: "use_aws_profile",
Label: "Use credentials from existing AWS profiles?",
Options: []string{awsPickProfile, awsManualInputCredentials},
},
customAwsPickProfileCondition,
NoValidation,
},
{
moduleconfig.Parameter{
Field: "aws_profile",
Label: "Select AWS Profile",
Options: profiles,
},
KeyMatchCondition("use_aws_profile", awsPickProfile),
NoValidation,
},
{
moduleconfig.Parameter{
Field: "accessKeyId",
Label: "AWS Access Key ID",
Default: projectCred.AWSResourceConfig.AccessKeyId,
},
CustomCondition(customAwsMustInputCondition),
project.ValidateAKID,
},
{
moduleconfig.Parameter{
Field: "secretAccessKey",
Label: "AWS Secret access key",
Default: projectCred.AWSResourceConfig.SecretAccessKey,
},
CustomCondition(customAwsMustInputCondition),
project.ValidateSAK,
},
}
prompts = append(prompts, awsPrompts...)
case "github":
githubPrompt := PromptHandler{
moduleconfig.Parameter{
Field: "accessToken",
Label: "Github Personal Access Token with access to the above organization",
Default: projectCred.GithubResourceConfig.AccessToken,
},
NoCondition,
NoValidation,
}
prompts = append(prompts, githubPrompt)
case "circleci":
circleCiPrompt := PromptHandler{
moduleconfig.Parameter{
Field: "apiKey",
Label: "Circleci api key for CI/CD",
Default: projectCred.CircleCiResourceConfig.ApiKey,
},
NoCondition,
NoValidation,
}
prompts = append(prompts, circleCiPrompt)
}
return prompts
}
func chooseCloudProvider(projectConfig *projectconfig.ZeroProjectConfig) {
// @TODO move options into configs
providerPrompt := promptui.Select{
Label: "Select Cloud Provider",
Items: []string{"Amazon AWS", "Google GCP", "Microsoft Azure"},
}
_, providerResult, err := providerPrompt.Run()
if err != nil {
exit.Fatal("Prompt failed %v\n", err)
}
if providerResult != "Amazon AWS" {
exit.Fatal("Only the AWS provider is available at this time")
}
}
func chooseStack(reg registry.Registry) []string {
providerPrompt := promptui.Select{
Label: "Pick a stack you'd like to use",
Items: registry.AvailableLabels(reg),
}
_, providerResult, err := providerPrompt.Run()
if err != nil {
exit.Fatal("Prompt failed %v\n", err)
}
return registry.GetModulesByName(reg, providerResult)
}
func fillProviderDetails(projectConfig *projectconfig.ZeroProjectConfig, s project.Secrets) {
if projectConfig.Infrastructure.AWS != nil {
sess, err := session.NewSession(&aws.Config{
Region: aws.String(projectConfig.Infrastructure.AWS.Region),
Credentials: credentials.NewStaticCredentials(s.AWS.AccessKeyID, s.AWS.SecretAccessKey, ""),
})
svc := sts.New(sess)
input := &sts.GetCallerIdentityInput{}
awsCaller, err := svc.GetCallerIdentity(input)
if err != nil {
if aerr, ok := err.(awserr.Error); ok {
switch aerr.Code() {
default:
exit.Error(aerr.Error())
}
} else {
exit.Error(err.Error())
}
}
if awsCaller != nil && awsCaller.Account != nil {
projectConfig.Infrastructure.AWS.AccountID = *awsCaller.Account
}
}
}
func defaultProjConfig() projectconfig.ZeroProjectConfig {
return projectconfig.ZeroProjectConfig{
Name: "",
Infrastructure: projectconfig.Infrastructure{
AWS: nil,
},
Parameters: map[string]string{},
Modules: projectconfig.Modules{},
}
}