-
Notifications
You must be signed in to change notification settings - Fork 787
/
install.go
2637 lines (2357 loc) · 87.2 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
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package cmd
import (
"encoding/base64"
"fmt"
"io"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"time"
"gopkg.in/yaml.v2"
"github.com/Pallinder/go-randomdata"
"github.com/jenkins-x/jx/pkg/io/secrets"
kubevault "github.com/jenkins-x/jx/pkg/kube/vault"
"github.com/jenkins-x/jx/pkg/vault"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io"
"github.com/jenkins-x/jx/pkg/addon"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/auth"
"github.com/jenkins-x/jx/pkg/cloud/aks"
"github.com/jenkins-x/jx/pkg/cloud/amazon"
"github.com/jenkins-x/jx/pkg/cloud/iks"
"github.com/jenkins-x/jx/pkg/config"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/helm"
configio "github.com/jenkins-x/jx/pkg/io"
"github.com/jenkins-x/jx/pkg/jx/cmd/templates"
"github.com/jenkins-x/jx/pkg/kube"
"github.com/jenkins-x/jx/pkg/log"
"github.com/jenkins-x/jx/pkg/util"
"github.com/pkg/errors"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1"
"gopkg.in/AlecAivazis/survey.v1/terminal"
"gopkg.in/src-d/go-git.v4"
core_v1 "k8s.io/api/core/v1"
storagev1 "k8s.io/api/storage/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/client-go/kubernetes"
)
// ModifySecretCallback a callback for modifying a Secret for a given name
type ModifySecretCallback func(string, func(*core_v1.Secret) error) (*core_v1.Secret, error)
// ModifyConfigMapCallback a callback for modifying a ConfigMap for a given name
type ModifyConfigMapCallback func(string, func(*core_v1.ConfigMap) error) (*core_v1.ConfigMap, error)
// InstallOptions 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
modifyConfigMapCallback ModifyConfigMapCallback
modifySecretCallback ModifySecretCallback
installValues map[string]string
}
// InstallFlags flags for the install command
type InstallFlags struct {
Domain string
ExposeControllerPathMode string
DockerRegistry string
Provider string
CloudEnvRepository string
LocalHelmRepoName string
Namespace string
NoDefaultEnvironments bool
HelmTLS bool
DefaultEnvironmentPrefix string
LocalCloudEnvironment bool
Timeout string
RegisterLocalHelmRepo bool
CleanupTempFiles bool
InstallOnly bool
EnvironmentGitOwner string
Version string
Prow bool
DisableSetKubeContext bool
GitOpsMode bool
Dir string
NoGitOpsEnvApply bool
NoGitOpsEnvRepo bool
NoGitOpsVault bool
Vault bool
BuildPackName string
}
// Secrets struct for secrets
type Secrets struct {
Login string
Token string
}
const (
JX_GIT_TOKEN = "JX_GIT_TOKEN"
JX_GIT_USER = "JX_GIT_USER"
// Want to use your own provider file? Change this line to point to your fork
DefaultCloudEnvironmentsURL = "https://github.com/jenkins-x/cloud-environments"
// JenkinsXPlatformChartName default chart name for Jenkins X platform
JenkinsXPlatformChartName = "jenkins-x-platform"
// JenkinsXPlatformChart the default full chart name with the default repository prefix
JenkinsXPlatformChart = "jenkins-x/" + JenkinsXPlatformChartName
JenkinsXPlatformRelease = "jenkins-x"
AdminSecretsFile = "adminSecrets.yaml"
ExtraValuesFile = "extraValues.yaml"
JXInstallConfig = "jx-install-config"
CloudEnvValuesFile = "myvalues.yaml"
CloudEnvSecretsFile = "secrets.yaml"
CloudEnvSopsConfigFile = ".sops.yaml"
defaultInstallTimeout = "6000"
ServerlessJenkins = "Serverless Jenkins"
StaticMasterJenkins = "Static Master Jenkins"
GitOpsChartYAML = `name: env
version: 0.0.1
description: GitOps Environment for this Environment
maintainers:
- name: Team
icon: https://www.cloudbees.com/sites/default/files/Jenkins_8.png
`
devGitOpsGitIgnore = `
# lets not accidentally check in Secret YAMLs!
secrets.yaml
mysecrets.yaml
`
devGitOpsReadMe = `
## Jenkins X Development Environment
This repository contains the source code for the Jenkins X Development Environment so that it can be managed via GitOps.
`
devGitOpsJenkinsfile = `pipeline {
agent {
label "jenkins-jx-base"
}
environment {
DEPLOY_NAMESPACE = "%s"
}
stages {
stage('Validate Environment') {
steps {
container('jx-base') {
dir('env') {
sh 'jx step helm build'
}
}
}
}
stage('Update Environment') {
when {
branch 'master'
}
steps {
container('jx-base') {
dir('env') {
sh 'jx step env apply'
}
}
}
}
}
}
`
devGitOpsJenkinsfileProw = `pipeline {
agent any
environment {
DEPLOY_NAMESPACE = "%s"
}
stages {
stage('Validate Environment') {
steps {
dir('env') {
sh 'jx step helm build'
}
}
}
stage('Update Environment') {
when {
branch 'master'
}
steps {
dir('env') {
sh 'jx step env apply'
}
}
}
}
}
`
)
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: [https://jenkins-x.io/getting-started/install-on-cluster/](https://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
`)
)
// NewCmdInstall creates a command object for the generic "install" action, which
// installs the jenkins-x platform on a Kubernetes cluster.
func NewCmdInstall(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) *cobra.Command {
options := CreateInstallOptions(f, in, 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()
CheckErr(err)
},
}
options.addCommonFlags(cmd)
options.addInstallFlags(cmd, false)
cmd.Flags().StringVarP(&options.Flags.Provider, "provider", "", "", "Cloud service providing the Kubernetes cluster. Supported providers: "+KubernetesProviderOptions())
cmd.AddCommand(NewCmdInstallDependencies(f, in, out, errOut))
return cmd
}
// CreateInstallOptions creates the options for jx install
func CreateInstallOptions(f Factory, in terminal.FileReader, out terminal.FileWriter, errOut io.Writer) InstallOptions {
commonOptions := CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
}
options := InstallOptions{
CreateJenkinsUserOptions: CreateJenkinsUserOptions{
Username: "admin",
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
In: in,
Out: out,
Err: errOut,
Headless: true,
},
},
},
GitRepositoryOptions: gits.GitRepositoryOptions{},
CommonOptions: commonOptions,
CreateEnvOptions: CreateEnvOptions{
HelmValuesConfig: config.HelmValuesConfig{
ExposeController: &config.ExposeController{
Config: config.ExposeControllerConfig{
HTTP: "true",
TLSAcme: "false",
Exposer: "Ingress",
},
},
},
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,
In: in,
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
flags.addCloudEnvOptions(cmd)
cmd.Flags().StringVarP(&flags.LocalHelmRepoName, "local-helm-repo-name", "", kube.LocalHelmRepoName, "The name of the helm repository for the installed ChartMuseum")
cmd.Flags().BoolVarP(&flags.NoDefaultEnvironments, "no-default-environments", "", false, "Disables the creation of the 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().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().StringVarP(&flags.EnvironmentGitOwner, "environment-git-owner", "", "", "The Git provider organisation to create the environment Git repositories in")
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]")
cmd.Flags().BoolVarP(&flags.HelmTLS, "helm-tls", "", false, "Whether to use TLS with helm")
cmd.Flags().BoolVarP(&flags.InstallOnly, "install-only", "", false, "Force the install command to fail if there is already an installation. Otherwise lets update the installation")
cmd.Flags().StringVarP(&flags.DockerRegistry, "docker-registry", "", "", "The Docker Registry host or host:port which is used when tagging and pushing images. If not specified it defaults to the internal registry unless there is a better provider default (e.g. ECR on AWS/EKS)")
cmd.Flags().StringVarP(&flags.ExposeControllerPathMode, "exposecontroller-pathmode", "", "", "The ExposeController path mode for how services should be exposed as URLs. Defaults to using subnets. Use a value of `path` to use relative paths within the domain host such as when using AWS ELB host names")
cmd.Flags().StringVarP(&flags.Version, "version", "", "", "The specific platform version to install")
cmd.Flags().BoolVarP(&flags.Prow, "prow", "", false, "Enable Prow")
cmd.Flags().BoolVarP(&flags.GitOpsMode, "gitops", "", false, "Sets up the local file system for GitOps so that the current installation can be configured or upgraded at any time via GitOps")
cmd.Flags().BoolVarP(&flags.NoGitOpsEnvApply, "no-gitops-env-apply", "", false, "When using GitOps to create the source code for the development environment and installation, don't run 'jx step env apply' to perform the install")
cmd.Flags().BoolVarP(&flags.NoGitOpsEnvRepo, "no-gitops-env-repo", "", false, "When using GitOps to create the source code for the development environment this flag disables the creation of a git repository for the source code")
cmd.Flags().BoolVarP(&flags.NoGitOpsVault, "no-gitops-vault", "", false, "When using GitOps to create the source code for the development environment this flag disables the creation of a vault")
cmd.Flags().BoolVarP(&flags.Vault, "vault", "", false, "Sets up a Hashicorp Vault for storing secrets during installation (supported only for GKE)")
cmd.Flags().StringVarP(&flags.BuildPackName, "buildpack", "", "", "The name of the build pack to use for the Team")
addGitRepoOptionsArguments(cmd, &options.GitRepositoryOptions)
options.HelmValuesConfig.AddExposeControllerValues(cmd, true)
options.AdminSecretsService.AddAdminSecretsValues(cmd)
options.InitOptions.addInitFlags(cmd)
}
func (flags *InstallFlags) addCloudEnvOptions(cmd *cobra.Command) {
cmd.Flags().StringVarP(&flags.CloudEnvRepository, "cloud-environment-repo", "", DefaultCloudEnvironmentsURL, "Cloud Environments Git repo")
cmd.Flags().BoolVarP(&flags.LocalCloudEnvironment, "local-cloud-environment", "", false, "Ignores default cloud-environment-repo and uses current directory ")
}
// Run implements this command
func (options *InstallOptions) Run() error {
configStore := configio.NewFileStore()
// Default to verbose mode to get more information during the install
options.Verbose = true
client, originalNs, err := options.KubeClientAndNamespace()
if err != nil {
return errors.Wrap(err, "creating the kube client")
}
ns := options.Flags.Namespace
if ns == "" {
ns = originalNs
}
options.SetDevNamespace(ns)
err = options.registerAllCRDs()
if err != nil {
return errors.Wrap(err, "registering all CRDs")
}
gitOpsDir, gitOpsEnvDir, err := options.configureGitOpsMode(configStore, ns)
if err != nil {
return errors.Wrap(err, "configuring the GitOps mode")
}
options.configureHelm(client, originalNs)
err = options.installHelmBinaries()
if err != nil {
return errors.Wrap(err, "installing helm binaries")
}
err = options.installCloudProviderDependencies()
if err != nil {
return errors.Wrap(err, "installing cloud provider dependencies")
}
err = options.configureKubectl(ns)
if err != nil {
return errors.Wrap(err, "configure the kubectl")
}
options.Flags.Provider, err = options.GetCloudProvider(options.Flags.Provider)
if err != nil {
return errors.Wrapf(err, "retrieving cloud provider '%s'", options.Flags.Provider)
}
options.setInstallValues(map[string]string{
kube.KubeProvider: options.Flags.Provider,
})
err = options.setMinikubeFromContext()
if err != nil {
return errors.Wrap(err, "configuring minikube from kubectl context")
}
err = options.storeInstallValues(client, ns)
if err != nil {
return errors.Wrap(err, "storing the install values")
}
err = options.configureCloudProviderPreInit(client)
if err != nil {
return errors.Wrap(err, "configuring the cloud provider before initializing the platform")
}
err = options.configureTeamSettings()
if err != nil {
return errors.Wrap(err, "configuring the team settings in the dev environment")
}
err = options.init()
if err != nil {
return errors.Wrap(err, "initializing the Jenkins X platform")
}
err = options.configureCloudProivderPostInit(client, ns)
if err != nil {
return errors.Wrap(err, "configuring the cloud provider after initializing the platform")
}
ic, err := options.saveIngressConfig()
if err != nil {
return errors.Wrap(err, "saving the ingress configuration in a ConfigMap")
}
err = options.saveClusterConfig()
if err != nil {
return errors.Wrap(err, "saving the cluster configuration in a ConfigMap")
}
err = options.createSystemVault(client, ns, ic)
if err != nil {
return errors.Wrap(err, "creating the system vault")
}
err = options.configureGitAuth()
if err != nil {
return errors.Wrap(err, "configuring the git auth")
}
err = options.configureDockerRegistry(client, ns)
if err != nil {
return errors.Wrap(err, "configuring the docker registry")
}
cloudEnvDir, err := options.cloneJXCloudEnvironmentsRepo()
if err != nil {
return errors.Wrap(err, "cloning the jx cloud environments repo")
}
err = options.configureHelmValues(ns)
if err != nil {
return errors.Wrap(err, "configuring helm values")
}
if options.Flags.Provider == "" {
return fmt.Errorf("no Kubernetes provider found to match cloud-environment with")
}
providerEnvDir := filepath.Join(cloudEnvDir, fmt.Sprintf("env-%s", strings.ToLower(options.Flags.Provider)))
valuesFiles, secretsFiles, temporaryFiles, err := options.getHelmValuesFiles(configStore, providerEnvDir)
if err != nil {
return errors.Wrap(err, "getting the helm value files")
}
log.Infof("Installing Jenkins X platform helm chart from: %s\n", providerEnvDir)
err = options.configureHelmRepo()
if err != nil {
return errors.Wrap(err, "configuring the Jenkins X helm repository")
}
err = options.selectJenkinsInstallation()
if err != nil {
return errors.Wrap(err, "selecting the Jenkins installation type")
}
err = options.configureAndInstallProw(ns)
if err != nil {
return errors.Wrap(err, "configuring and installing Prow")
}
err = options.verifyTiller(client, ns)
if err != nil {
return errors.Wrap(err, "verifying Tiller is running")
}
err = options.configureBuildPackMode()
if err != nil {
return errors.Wrap(err, "configuring the build pack mode")
}
log.Infof("Installing jx into namespace %s\n", util.ColorInfo(ns))
version, err := options.getPlatformVersion(cloudEnvDir, configStore)
if err != nil {
return errors.Wrap(err, "getting the platform version")
}
log.Infof("Installing jenkins-x-platform version: %s\n", util.ColorInfo(version))
if options.Flags.GitOpsMode {
err := options.installPlatformGitOpsMode(gitOpsEnvDir, gitOpsDir, configStore, DEFAULT_CHARTMUSEUM_URL,
JenkinsXPlatformChartName, ns, version, valuesFiles, secretsFiles)
if err != nil {
return errors.Wrap(err, "installing the Jenkins X platform in GitOps mode")
}
} else {
err := options.installPlatform(providerEnvDir, JenkinsXPlatformChart, JenkinsXPlatformRelease,
ns, version, valuesFiles, secretsFiles)
if err != nil {
return errors.Wrap(err, "installing the Jenkins X platform")
}
}
if options.Flags.CleanupTempFiles {
err := options.cleanupTempFiles(temporaryFiles)
if err != nil {
return errors.Wrap(err, "cleaning up the temporary files")
}
}
err = options.configureProwInTeamSettings()
if err != nil {
return errors.Wrap(err, "configuring Prow in team settings")
}
err = options.configureTillerInDevEnvironment()
if err != nil {
return errors.Wrap(err, "configuring Tiller in the dev environment")
}
err = options.configureHelm3(ns)
if err != nil {
return errors.Wrap(err, "configuring helm3")
}
err = options.installAddons()
if err != nil {
return errors.Wrap(err, "installing the Jenkins X Addons")
}
options.logAdminPassword()
err = options.configureJenkins(ns)
if err != nil {
return errors.Wrap(err, "configuring Jenkins")
}
err = options.createEnvironments(ns)
if err != nil {
return errors.Wrap(err, "creating the environments")
}
err = options.saveChartmuseumAuthConfig()
if err != nil {
return errors.Wrap(err, "saving the ChartMuseum auth configuration")
}
if options.Flags.RegisterLocalHelmRepo {
err = options.registerLocalHelmRepo(options.Flags.LocalHelmRepoName, ns)
if err != nil {
return errors.Wrapf(err, "registering the local helm repo '%s'", options.Flags.LocalHelmRepoName)
}
}
err = options.generateGitOpsDevEnvironmentConfig(gitOpsDir)
if err != nil {
return errors.Wrap(err, "generating the GitOps development environment config")
}
err = options.applyGitOpsDevEnvironmentConfig(gitOpsEnvDir, ns)
if err != nil {
return errors.Wrap(err, "applying the GitOps development environment config")
}
log.Successf("\nJenkins X installation completed successfully")
options.logAdminPassword()
log.Infof("\nYour Kubernetes context is now set to the namespace: %s \n", util.ColorInfo(ns))
log.Infof("To switch back to your original namespace use: %s\n", util.ColorInfo("jx namespace "+originalNs))
log.Infof("For help on switching contexts see: %s\n\n", util.ColorInfo("https://jenkins-x.io/developing/kube-context/"))
log.Infof("To import existing projects into Jenkins: %s\n", util.ColorInfo("jx import"))
log.Infof("To create a new Spring Boot microservice: %s\n", util.ColorInfo("jx create spring -d web -d actuator"))
log.Infof("To create a new microservice from a quickstart: %s\n", util.ColorInfo("jx create quickstart"))
return nil
}
func (options *InstallOptions) configureKubectl(namespace string) error {
context := ""
var err error
if !options.Flags.DisableSetKubeContext {
context, err = options.getCommandOutput("", "kubectl", "config", "current-context")
if err != nil {
return errors.Wrap(err, "failed to retrieve the current context from kube configuration")
}
}
if !options.Flags.DisableSetKubeContext {
err = options.RunCommand("kubectl", "config", "set-context", context, "--namespace", namespace)
if err != nil {
return errors.Wrapf(err, "failed to set the context '%s' in kube configuration", context)
}
}
return nil
}
func (options *InstallOptions) init() error {
initOpts := &options.InitOptions
initOpts.Flags.Provider = options.Flags.Provider
initOpts.Flags.Namespace = options.Flags.Namespace
initOpts.BatchMode = options.BatchMode
initOpts.Flags.Http = true
exposeController := options.CreateEnvOptions.HelmValuesConfig.ExposeController
if exposeController != nil {
initOpts.Flags.Http = exposeController.Config.HTTP == "true"
}
if initOpts.Flags.Domain == "" && options.Flags.Domain != "" {
initOpts.Flags.Domain = options.Flags.Domain
}
if initOpts.Flags.NoTiller {
initOpts.helm = nil
}
// configure local tiller if this is required
if !initOpts.Flags.RemoteTiller && !initOpts.Flags.NoTiller {
err := restartLocalTiller()
if err != nil {
return errors.Wrap(err, "restarting local tiller")
}
initOpts.helm = options.helm
}
// configure the helm values for expose controller
if exposeController != nil {
ecConfig := &exposeController.Config
if ecConfig.Domain == "" && options.Flags.Domain != "" {
ecConfig.Domain = options.Flags.Domain
log.Success("set exposeController Config Domain " + ecConfig.Domain + "\n")
}
if ecConfig.PathMode == "" && options.Flags.ExposeControllerPathMode != "" {
ecConfig.PathMode = options.Flags.ExposeControllerPathMode
log.Success("set exposeController Config PathMode " + ecConfig.PathMode + "\n")
}
if isOpenShiftProvider(options.Flags.Provider) {
ecConfig.Exposer = "Route"
}
}
err := initOpts.Run()
if err != nil {
return errors.Wrap(err, "initializing the Jenkins X platform")
}
// update the domain if was modified during the initialization
domain := exposeController.Config.Domain
if domain == "" {
domain = initOpts.Flags.Domain
}
if domain == "" {
client, err := options.KubeClient()
if err != nil {
return errors.Wrap(err, "getting the kubernetes client")
}
ingNamespace := initOpts.Flags.IngressNamespace
ingService := initOpts.Flags.IngressService
extIP := initOpts.Flags.ExternalIP
domain, err = options.GetDomain(client, domain,
options.Flags.Provider,
ingNamespace,
ingService,
extIP)
if err != nil {
return errors.Wrapf(err, "getting a domain for ingress service %s/%s", ingNamespace, ingService)
}
}
// checking if the domain is by any chance empty and bail out
if domain == "" {
return fmt.Errorf("the installation cannot proceed with an empty domain. Please provide a domain in the %s option",
util.ColorInfo("domain"))
}
options.Flags.Domain = domain
exposeController.Config.Domain = domain
return nil
}
func (options *InstallOptions) getPlatformVersion(cloudEnvDir string,
configStore configio.ConfigStore) (string, error) {
version := options.Flags.Version
var err error
if version == "" {
version, err = LoadVersionFromCloudEnvironmentsDir(cloudEnvDir, configStore)
if err != nil {
return "", errors.Wrap(err, "failed to load version from cloud environments dir")
}
}
return version, nil
}
func (options *InstallOptions) installPlatform(providerEnvDir string, jxChart string, jxRelName string,
namespace string, version string, valuesFiles []string, secretsFiles []string) error {
options.Helm().SetCWD(providerEnvDir)
timeout := options.Flags.Timeout
if timeout == "" {
timeout = defaultInstallTimeout
}
timeoutInt, err := strconv.Atoi(timeout)
if err != nil {
return errors.Wrap(err, "failed to convert the helm install timeout value")
}
allValuesFiles := []string{}
allValuesFiles = append(allValuesFiles, valuesFiles...)
allValuesFiles = append(allValuesFiles, secretsFiles...)
for _, f := range allValuesFiles {
options.Debugf("Adding values file %s\n", util.ColorInfo(f))
}
if !options.Flags.InstallOnly {
err = options.Helm().UpgradeChart(jxChart, jxRelName, namespace, &version, true,
&timeoutInt, false, false, nil, allValuesFiles, "", "", "")
} else {
err = options.Helm().InstallChart(jxChart, jxRelName, namespace, &version, &timeoutInt,
nil, allValuesFiles, "", "", "")
}
if err != nil {
return errors.Wrap(err, "failed to install/upgrade the jenkins-x platform chart")
}
err = options.waitForInstallToBeReady(namespace)
if err != nil {
return errors.Wrap(err, "failed to wait for jenkins-x chart installation to be ready")
}
log.Infof("Jenkins X deployments ready in namespace %s\n", namespace)
return nil
}
func (options *InstallOptions) installPlatformGitOpsMode(gitOpsEnvDir string, gitOpsDir string, configStore configio.ConfigStore,
chartRepository string, chartName string, namespace string, version string, valuesFiles []string, secretsFiles []string) error {
options.CreateEnvOptions.NoDevNamespaceInit = true
deps := []*helm.Dependency{
{
Name: JenkinsXPlatformChartName,
Version: version,
Repository: DEFAULT_CHARTMUSEUM_URL,
},
}
requirements := &helm.Requirements{
Dependencies: deps,
}
chartFile := filepath.Join(gitOpsEnvDir, helm.ChartFileName)
requirementsFile := filepath.Join(gitOpsEnvDir, helm.RequirementsFileName)
secretsFile := filepath.Join(gitOpsEnvDir, helm.SecretsFileName)
valuesFile := filepath.Join(gitOpsEnvDir, helm.ValuesFileName)
err := helm.SaveFile(requirementsFile, requirements)
if err != nil {
return errors.Wrapf(err, "failed to save GitOps helm requirements file %s", requirementsFile)
}
err = configStore.Write(chartFile, []byte(GitOpsChartYAML))
if err != nil {
return errors.Wrapf(err, "failed to save file %s", chartFile)
}
err = helm.CombineValueFilesToFile(secretsFile, secretsFiles, JenkinsXPlatformChartName, nil)
if err != nil {
return errors.Wrapf(err, "failed to generate %s by combining helm Secret YAML files %s", secretsFile, strings.Join(secretsFiles, ", "))
}
if options.Flags.Vault {
err := options.storeSecretYamlFilesInVault(vault.GitOpsSecretsPath, secretsFile)
if err != nil {
return errors.Wrapf(err, "storing in Vault the secrets files: %s", secretsFile)
}
err = util.DestroyFile(secretsFile)
if err != nil {
return errors.Wrapf(err, "destroying the secrets file '%s' after storing it in Vault", secretsFile)
}
}
extraValues := map[string]interface{}{
"postinstalljob": map[string]interface{}{"enabled": "true"},
}
err = helm.CombineValueFilesToFile(valuesFile, valuesFiles, JenkinsXPlatformChartName, extraValues)
if err != nil {
return errors.Wrapf(err, "failed to generate %s by combining helm value YAML files %s", valuesFile, strings.Join(valuesFiles, ", "))
}
gitIgnore := filepath.Join(gitOpsDir, ".gitignore")
err = configStore.Write(gitIgnore, []byte(devGitOpsGitIgnore))
if err != nil {
return errors.Wrapf(err, "failed to write %s", gitIgnore)
}
readme := filepath.Join(gitOpsDir, "README.md")
err = configStore.Write(readme, []byte(devGitOpsReadMe))
if err != nil {
return errors.Wrapf(err, "failed to write %s", readme)
}
jenkinsFile := filepath.Join(gitOpsDir, "Jenkinsfile")
jftTmp := devGitOpsJenkinsfile
isProw := options.Flags.Prow
if isProw {
jftTmp = devGitOpsJenkinsfileProw
}
text := fmt.Sprintf(jftTmp, namespace)
err = configStore.Write(jenkinsFile, []byte(text))
if err != nil {
return errors.Wrapf(err, "failed to write %s", jenkinsFile)
}
return nil
}
func (options *InstallOptions) configureAndInstallProw(namespace string) error {
options.currentNamespace = namespace
if options.Flags.Prow {
_, pipelineUser, err := options.getPipelineGitAuth()
if err != nil {
return errors.Wrap(err, "retrieving the pipeline Git Auth")
}
options.OAUTHToken = pipelineUser.ApiToken
err = options.installProw()
if err != nil {
errors.Wrap(err, "installing Prow")
}
}
return nil
}
func (options *InstallOptions) configureHelm3(namespace string) error {
initOpts := &options.InitOptions
helmBinary := initOpts.HelmBinary()
if helmBinary != "helm" {
helmOptions := EditHelmBinOptions{}
helmOptions.CommonOptions = options.CommonOptions
helmOptions.CommonOptions.BatchMode = true
helmOptions.CommonOptions.Args = []string{helmBinary}
helmOptions.currentNamespace = namespace
helmOptions.devNamespace = namespace
err := helmOptions.Run()
if err != nil {
return errors.Wrap(err, "failed to edit the helm options")
}
}
return nil
}
func (options *InstallOptions) configureHelm(client kubernetes.Interface, namespace string) {
initOpts := &options.InitOptions
helmBinary := initOpts.HelmBinary()
options.Helm().SetHelmBinary(helmBinary)
if initOpts.Flags.NoTiller {
helmer := options.Helm()
helmCli, ok := helmer.(*helm.HelmCLI)
if ok && helmCli != nil {
options.helm = helm.NewHelmTemplate(helmCli, helmCli.CWD, client, namespace)
} else {
helmTemplate, ok := helmer.(*helm.HelmTemplate)
if ok {
options.helm = helmTemplate
} else {
log.Warnf("Helm facade is not a *helm.HelmCLI or *helm.HelmTemplate: %#v\n", helmer)
}
}
}
}
func (options *InstallOptions) configureHelmRepo() error {
err := options.addHelmBinaryRepoIfMissing(DEFAULT_CHARTMUSEUM_URL, "jenkins-x", "", "")
if err != nil {
return errors.Wrap(err, "failed to add the jenkinx-x helm repo")
}
err = options.Helm().UpdateRepo()
if err != nil {
return errors.Wrap(err, "failed to update the helm repo")
}
return nil
}
func (options *InstallOptions) selectJenkinsInstallation() error {
if !options.BatchMode && !options.Flags.Prow {
jenkinsInstallOptions := []string{
ServerlessJenkins,
StaticMasterJenkins,
}
jenkinsInstallOption, err := util.PickNameWithDefault(jenkinsInstallOptions, "Select Jenkins installation type:", StaticMasterJenkins, "", options.In, options.Out, options.Err)
if err != nil {
return errors.Wrap(err, "picking Jenkins installation type")
}
if jenkinsInstallOption == ServerlessJenkins {
options.Flags.Prow = true
}
}
return nil
}
func (options *InstallOptions) configureTillerNamespace() error {
helmConfig := &options.CreateEnvOptions.HelmValuesConfig
initOpts := &options.InitOptions
if initOpts.Flags.TillerNamespace != "" {
if helmConfig.Jenkins.Servers.Global.EnvVars == nil {
helmConfig.Jenkins.Servers.Global.EnvVars = map[string]string{}
}
helmConfig.Jenkins.Servers.Global.EnvVars["TILLER_NAMESPACE"] = initOpts.Flags.TillerNamespace
os.Setenv("TILLER_NAMESPACE", initOpts.Flags.TillerNamespace)
}
return nil
}
func (options *InstallOptions) configureHelmValues(namespace string) error {
helmConfig := &options.CreateEnvOptions.HelmValuesConfig
domain := helmConfig.ExposeController.Config.Domain
if domain != "" && addon.IsAddonEnabled("gitea") {
helmConfig.Jenkins.Servers.GetOrCreateFirstGitea().Url = "http://gitea-gitea." + namespace + "." + domain
}
err := options.addGitServersToJenkinsConfig(helmConfig)
if err != nil {
return errors.Wrap(err, "configuring the Git Servers into Jenkins configuration")
}
err = options.configureTillerNamespace()
if err != nil {
return errors.Wrap(err, "configuring the tiller namespace")
}
if !options.Flags.GitOpsMode {
options.SetDevNamespace(namespace)
}
isProw := options.Flags.Prow
if isProw {
enableJenkins := false
helmConfig.Jenkins.Enabled = &enableJenkins
enableControllerBuild := true
helmConfig.ControllerBuild.Enabled = &enableControllerBuild
}
return nil
}
func (options *InstallOptions) getHelmValuesFiles(configStore configio.ConfigStore, providerEnvDir string) ([]string, []string, []string, error) {
helmConfig := &options.CreateEnvOptions.HelmValuesConfig
cloudEnvironmentValuesLocation := filepath.Join(providerEnvDir, CloudEnvValuesFile)
cloudEnvironmentSecretsLocation := filepath.Join(providerEnvDir, CloudEnvSecretsFile)
valuesFiles := []string{}
secretsFiles := []string{}
temporaryFiles := []string{}
adminSecretsFileName, adminSecrets, err := options.getAdminSecrets(configStore,
providerEnvDir, cloudEnvironmentSecretsLocation)
if err != nil {
return valuesFiles, secretsFiles, temporaryFiles,
errors.Wrap(err, "creating the admin secrets")
}
dir, err := util.ConfigDir()
if err != nil {
return valuesFiles, secretsFiles, temporaryFiles,
errors.Wrap(err, "creating a temporary config dir for Git credentials")
}