-
Notifications
You must be signed in to change notification settings - Fork 1
/
install.go
602 lines (518 loc) · 17.8 KB
/
install.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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
package cmd
import (
"fmt"
"io"
"io/ioutil"
"os"
"path/filepath"
"strings"
"time"
"github.com/Pallinder/go-randomdata"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/config"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/jx/cmd/log"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
cmdutil "github.com/jenkins-x/jx/pkg/jx/cmd/util"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/util"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1"
"gopkg.in/src-d/go-git.v4"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
// GetOptions is the start of the data required to perform the operation. As new fields are added, add them here instead of
// referencing the cmd.Flags()
type InstallOptions struct {
CommonOptions
gits.GitRepositoryOptions
CreateJenkinsUserOptions
CreateEnvOptions
config.AdminSecretsService
InitOptions InitOptions
Flags InstallFlags
}
type InstallFlags struct {
Domain string
Provider string
CloudEnvRepository string
LocalHelmRepoName string
Namespace string
DefaultEnvironments bool
DefaultEnvironmentPrefix string
LocalCloudEnvironment bool
Timeout string
RegisterLocalHelmRepo bool
CleanupTempFiles bool
}
type Secrets struct {
Login string
Token string
}
const (
JX_GIT_TOKEN = "JX_GIT_TOKEN"
JX_GIT_USER = "JX_GIT_USER"
DEFAULT_CLOUD_ENVIRONMENTS_URL = "https://github.com/jenkins-x/cloud-environments"
GitSecretsFile = "gitSecrets.yaml"
AdminSecretsFile = "adminSecrets.yaml"
ExtraValuesFile = "extraValues.yaml"
defaultInstallTimeout = "6000"
)
var (
instalLong = templates.LongDesc(`
Installs the Jenkins X platform on a Kubernetes cluster
Requires a --git-username and --git-api-token that can be used to create a new token.
This is so the Jenkins X platform can git tag your releases
For more documentation see: [http://jenkins-x.io/getting-started/install-on-cluster/](http://jenkins-x.io/getting-started/install-on-cluster/)
The current requirements are:
* RBAC is enabled on the cluster
* insecure docker registry is enabled for docker registries running locally inside kubernetes on the service IP range. See the above documentation for more detail
`)
instalExample = templates.Examples(`
# Default installer which uses interactive prompts to generate git secrets
jx install
# Install with a GitHub personal access token
jx install --git-username jenkins-x-bot --git-api-token 9fdbd2d070cd81eb12bca87861bcd850
# If you know the cloud provider you can pass this as a CLI argument. E.g. for AWS
jx install --provider=aws
`)
)
// NewCmdGet creates a command object for the generic "install" action, which
// installs the jenkins-x platform on a kubernetes cluster.
func NewCmdInstall(f cmdutil.Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := createInstallOptions(f, out, errOut)
cmd := &cobra.Command{
Use: "install [flags]",
Short: "Install Jenkins X in the current Kubernetes cluster",
Long: instalLong,
Example: instalExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
cmdutil.CheckErr(err)
},
SuggestFor: []string{"list", "ps"},
}
options.addCommonFlags(cmd)
options.addInstallFlags(cmd, false)
cmd.Flags().StringVarP(&options.Flags.Provider, "provider", "", "", "Cloud service providing the kubernetes cluster. Supported providers: "+KubernetesProviderOptions())
return cmd
}
func createInstallOptions(f cmdutil.Factory, out io.Writer, errOut io.Writer) InstallOptions {
commonOptions := CommonOptions{
Factory: f,
Out: out,
Err: errOut,
}
options := InstallOptions{
CreateJenkinsUserOptions: CreateJenkinsUserOptions{
Username: "admin",
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
Headless: true,
},
},
},
GitRepositoryOptions: gits.GitRepositoryOptions{},
CommonOptions: commonOptions,
CreateEnvOptions: CreateEnvOptions{
HelmValuesConfig: config.HelmValuesConfig{
ExposeController: &config.ExposeController{},
},
Options: v1.Environment{
ObjectMeta: metav1.ObjectMeta{},
Spec: v1.EnvironmentSpec{
PromotionStrategy: v1.PromotionStrategyTypeAutomatic,
},
},
PromotionStrategy: string(v1.PromotionStrategyTypeAutomatic),
ForkEnvironmentGitRepo: kube.DefaultEnvironmentGitRepoURL,
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
Headless: true,
BatchMode: true,
},
},
},
InitOptions: InitOptions{
CommonOptions: commonOptions,
Flags: InitFlags{},
},
AdminSecretsService: config.AdminSecretsService{},
}
return options
}
func (options *InstallOptions) addInstallFlags(cmd *cobra.Command, includesInit bool) {
flags := &options.Flags
cmd.Flags().StringVarP(&flags.CloudEnvRepository, "cloud-environment-repo", "", DEFAULT_CLOUD_ENVIRONMENTS_URL, "Cloud Environments git repo")
cmd.Flags().StringVarP(&flags.LocalHelmRepoName, "local-helm-repo-name", "", kube.LocalHelmRepoName, "The name of the helm repository for the installed Chart Museum")
cmd.Flags().BoolVarP(&flags.DefaultEnvironments, "default-environments", "", true, "Creates default Staging and Production environments")
cmd.Flags().StringVarP(&flags.DefaultEnvironmentPrefix, "default-environment-prefix", "", "", "Default environment repo prefix, your git repos will be of the form 'environment-$prefix-$envName'")
cmd.Flags().BoolVarP(&flags.LocalCloudEnvironment, "local-cloud-environment", "", false, "Ignores default cloud-environment-repo and uses current directory ")
cmd.Flags().StringVarP(&flags.Namespace, "namespace", "", "jx", "The namespace the Jenkins X platform should be installed into")
cmd.Flags().StringVarP(&flags.Timeout, "timeout", "", defaultInstallTimeout, "The number of seconds to wait for the helm install to complete")
cmd.Flags().BoolVarP(&flags.RegisterLocalHelmRepo, "register-local-helmrepo", "", false, "Registers the Jenkins X chartmuseum registry with your helm client [default false]")
cmd.Flags().BoolVarP(&flags.CleanupTempFiles, "cleanup-temp-files", "", true, "Cleans up any temporary values.yaml used by helm install [default true]")
addGitRepoOptionsArguments(cmd, &options.GitRepositoryOptions)
options.HelmValuesConfig.AddExposeControllerValues(cmd, true)
options.AdminSecretsService.AddAdminSecretsValues(cmd)
options.InitOptions.addInitFlags(cmd)
}
// Run implements this command
func (options *InstallOptions) Run() error {
client, _, err := options.Factory.CreateClient()
if err != nil {
return err
}
options.kubeClient = client
context, err := options.getCommandOutput("", "kubectl", "config", "current-context")
if err != nil {
return err
}
ns := options.Flags.Namespace
if ns == "" {
f := options.Factory
_, ns, _ = f.CreateClient()
if err != nil {
return err
}
}
err = options.runCommand("kubectl", "config", "set-context", context, "--namespace", ns)
if err != nil {
return err
}
options.Flags.Provider, err = options.GetCloudProvider(options.Flags.Provider)
if err != nil {
return err
}
initOpts := &options.InitOptions
initOpts.Flags.Provider = options.Flags.Provider
initOpts.Flags.Namespace = options.Flags.Namespace
initOpts.BatchMode = options.BatchMode
if initOpts.Flags.Domain == "" && options.Flags.Domain != "" {
initOpts.Flags.Domain = options.Flags.Domain
}
err = initOpts.Run()
if err != nil {
return err
}
// share the init domain option with the install options
if initOpts.Flags.Domain != "" && options.Flags.Domain == "" {
options.Flags.Domain = initOpts.Flags.Domain
}
// get secrets to use in helm install
secrets, err := options.getGitSecrets()
if err != nil {
return err
}
err = options.AdminSecretsService.NewAdminSecretsConfig()
if err != nil {
return err
}
adminSecrets, err := options.AdminSecretsService.Secrets.String()
if err != nil {
return err
}
helmConfig := &options.CreateEnvOptions.HelmValuesConfig
if helmConfig.ExposeController.Config.Domain == "" {
helmConfig.ExposeController.Config.Domain = options.InitOptions.Flags.Domain
}
config, err := helmConfig.String()
if err != nil {
return err
}
// clone the environments repo
wrkDir := filepath.Join(util.HomeDir(), ".jx", "cloud-environments")
err = options.cloneJXCloudEnvironmentsRepo(wrkDir)
if err != nil {
return err
}
// run helm install setting the token and domain values
if options.Flags.Provider == "" {
return fmt.Errorf("No kubernetes provider found to match cloud-environment with")
}
makefileDir := filepath.Join(wrkDir, fmt.Sprintf("env-%s", strings.ToLower(options.Flags.Provider)))
if _, err := os.Stat(wrkDir); os.IsNotExist(err) {
return fmt.Errorf("cloud environment dir %s not found", makefileDir)
}
// create a temporary file that's used to pass current git creds to helm in order to create a secret for pipelines to tag releases
dir, err := util.ConfigDir()
if err != nil {
return err
}
secretsFileName := filepath.Join(dir, GitSecretsFile)
err = ioutil.WriteFile(secretsFileName, []byte(secrets), 0644)
if err != nil {
return err
}
adminSecretsFileName := filepath.Join(dir, AdminSecretsFile)
err = ioutil.WriteFile(adminSecretsFileName, []byte(adminSecrets), 0644)
if err != nil {
return err
}
configFileName := filepath.Join(dir, ExtraValuesFile)
err = ioutil.WriteFile(configFileName, []byte(config), 0644)
if err != nil {
return err
}
options.Printf("Generated helm values %s\n", util.ColorInfo(configFileName))
timeout := options.Flags.Timeout
if timeout == "" {
timeout = defaultInstallTimeout
}
arg := fmt.Sprintf("ARGS=--values=%s --values=%s --values=%s --namespace=%s --timeout=%s", secretsFileName, adminSecretsFileName, configFileName, ns, timeout)
// run the helm install
err = options.runCommandFromDir(makefileDir, "make", arg, "install")
if err != nil {
return err
}
if options.Flags.CleanupTempFiles {
err = os.Remove(secretsFileName)
if err != nil {
return err
}
err = os.Remove(configFileName)
if err != nil {
return err
}
}
err = options.waitForInstallToBeReady(ns)
if err != nil {
return err
}
log.Infof("Jenkins X deployments ready in namespace %s\n", ns)
options.logAdminPassword()
if options.Flags.DefaultEnvironments {
log.Info("Getting Jenkins API Token\n")
err = options.retry(3, 2*time.Second, func() (err error) {
options.CreateJenkinsUserOptions.Password = options.AdminSecretsService.Flags.DefaultAdminPassword
options.CreateJenkinsUserOptions.UseBrowser = true
err = options.CreateJenkinsUserOptions.Run()
return
})
if err != nil {
return err
}
if options.Flags.DefaultEnvironmentPrefix == "" {
options.Flags.DefaultEnvironmentPrefix = strings.ToLower(randomdata.SillyName())
}
log.Info("Creating default staging and production environments\n")
options.CreateEnvOptions.Options.Name = "staging"
options.CreateEnvOptions.Options.Spec.Label = "Staging"
options.CreateEnvOptions.Options.Spec.Order = 100
options.CreateEnvOptions.Prefix = options.Flags.DefaultEnvironmentPrefix
err = options.CreateEnvOptions.Run()
if err != nil {
return err
}
options.CreateEnvOptions.Options.Name = "production"
options.CreateEnvOptions.Options.Spec.Label = "Production"
options.CreateEnvOptions.Options.Spec.Order = 200
options.CreateEnvOptions.Options.Spec.PromotionStrategy = v1.PromotionStrategyTypeManual
options.CreateEnvOptions.PromotionStrategy = string(v1.PromotionStrategyTypeManual)
err = options.CreateEnvOptions.Run()
if err != nil {
return err
}
}
err = options.saveChartmuseumAuthConfig()
if err != nil {
return err
}
if options.Flags.RegisterLocalHelmRepo {
err = options.registerLocalHelmRepo(options.Flags.LocalHelmRepoName, ns)
if err != nil {
return err
}
}
log.Success("\nJenkins X installation completed successfully\n")
options.logAdminPassword()
options.Printf("\nTo import existing projects into Jenkins: %s\n", util.ColorInfo("jx import"))
options.Printf("To create a new Spring Boot microservice: %s\n", util.ColorInfo("jx create spring -d web -d actuator"))
return nil
}
func (options *InstallOptions) logAdminPassword() {
astrix := `
********************************************************
NOTE: %s
********************************************************
`
options.Printf(astrix, fmt.Sprintf("Your admin password is: %s", util.ColorInfo(options.AdminSecretsService.Flags.DefaultAdminPassword)))
}
// clones the jenkins-x cloud-environments repo to a local working dir
func (o *InstallOptions) cloneJXCloudEnvironmentsRepo(wrkDir string) error {
log.Infof("Cloning the Jenkins X cloud environments repo to %s\n", wrkDir)
if o.Flags.CloudEnvRepository == "" {
return fmt.Errorf("No cloud environment git URL")
}
if o.Flags.LocalCloudEnvironment {
currentDir, err := os.Getwd()
if err != nil {
return fmt.Errorf("error getting current working directory %v", err)
}
log.Infof("Copying local dir to %s\n", wrkDir)
return util.CopyDir(currentDir, wrkDir, true)
}
_, err := git.PlainClone(wrkDir, false, &git.CloneOptions{
URL: o.Flags.CloudEnvRepository,
ReferenceName: "refs/heads/master",
SingleBranch: true,
Progress: o.Out,
})
if err != nil {
if strings.Contains(err.Error(), "repository already exists") {
confirm := &survey.Confirm{
Message: "A local Jenkins X cloud environments repository already exists, recreate with latest?",
Default: true,
}
flag := false
err := survey.AskOne(confirm, &flag, nil)
if err != nil {
return err
}
if flag {
err := os.RemoveAll(wrkDir)
if err != nil {
return err
}
return o.cloneJXCloudEnvironmentsRepo(wrkDir)
}
} else {
return err
}
}
return nil
}
// returns secrets that are used as values during the helm install
func (o *InstallOptions) getGitSecrets() (string, error) {
username, token, err := o.getGitToken()
if err != nil {
return "", err
}
server := o.GitRepositoryOptions.ServerURL
if server == "" {
return "", fmt.Errorf("No Git Server found")
}
url := fmt.Sprintf("%s:%s@%s", username, token, server)
// TODO convert to a struct
pipelineSecrets := `
PipelineSecrets:
GitCreds: |-
https://%s
http://%s`
return fmt.Sprintf(pipelineSecrets, url, url), nil
}
// returns the Git Token that should be used by Jenkins X to setup credentials to clone repos and creates a secret for pipelines to tag a release
func (o *InstallOptions) getGitToken() (string, string, error) {
username := o.GitRepositoryOptions.Username
if username == "" {
if os.Getenv(JX_GIT_USER) != "" {
username = os.Getenv(JX_GIT_USER)
}
}
if username != "" {
// first check git-token flag
if o.GitRepositoryOptions.ApiToken != "" {
return username, o.GitRepositoryOptions.ApiToken, nil
}
// second check for an environment variable
if os.Getenv(JX_GIT_TOKEN) != "" {
return username, os.Getenv(JX_GIT_TOKEN), nil
}
}
o.Printf("Lets set up a git username and API token to be able to perform CI / CD\n\n")
userAuth, err := o.getGitUser("")
if err != nil {
return "", "", err
}
return userAuth.Username, userAuth.ApiToken, nil
}
func (o *InstallOptions) waitForInstallToBeReady(ns string) error {
f := o.Factory
client, _, err := f.CreateClient()
if err != nil {
return err
}
log.Warnf("waiting for install to be ready, if this is the first time then it will take a while to download images")
return kube.WaitForAllDeploymentsToBeReady(client, ns, 30*time.Minute)
}
func (options *InstallOptions) saveChartmuseumAuthConfig() error {
authConfigSvc, err := options.Factory.CreateChartmuseumAuthConfigService()
if err != nil {
return err
}
config := authConfigSvc.Config()
var server *auth.AuthServer
if options.ServerFlags.IsEmpty() {
url := ""
url, err = options.findService(kube.ServiceChartMuseum)
if err != nil {
return err
}
server = config.GetOrCreateServer(url)
} else {
server, err = options.findServer(config, &options.ServerFlags, "chartmuseum server", "Try installing one via: jx create team")
if err != nil {
return err
}
}
user := &auth.UserAuth{
Username: "admin",
Password: options.AdminSecretsService.Flags.DefaultAdminPassword,
}
server.Users = append(server.Users, user)
config.CurrentServer = server.URL
return authConfigSvc.SaveConfig()
}
func (o *InstallOptions) getGitUser(message string) (*auth.UserAuth, error) {
var userAuth *auth.UserAuth
authConfigSvc, err := o.Factory.CreateGitAuthConfigService()
if err != nil {
return userAuth, err
}
config := authConfigSvc.Config()
var server *auth.AuthServer
gitProvider := o.GitRepositoryOptions.ServerURL
if gitProvider != "" {
server = config.GetOrCreateServer(gitProvider)
} else {
server, err = config.PickServer("Which git provider?")
if err != nil {
return userAuth, err
}
}
url := server.URL
if message == "" {
fmt.Sprintf("%s username for CI/CD pipelines:", server.Label())
}
userAuth, err = config.PickServerUserAuth(server, message, o.BatchMode)
if err != nil {
return userAuth, err
}
if userAuth.IsInvalid() {
gits.PrintCreateRepositoryGenerateAccessToken(server, o.Out)
// TODO could we guess this based on the users ~/.git for github?
defaultUserName := ""
err = config.EditUserAuth(server.Label(), userAuth, defaultUserName, false, o.BatchMode)
if err != nil {
return userAuth, err
}
// TODO lets verify the auth works
err = authConfigSvc.SaveUserAuth(url, userAuth)
if err != nil {
return userAuth, fmt.Errorf("failed to store git auth configuration %s", err)
}
if userAuth.IsInvalid() {
return userAuth, fmt.Errorf("you did not properly define the user authentication")
}
}
return userAuth, nil
}