-
Notifications
You must be signed in to change notification settings - Fork 787
/
install.go
2118 lines (1909 loc) · 70.5 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"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/jenkins-x/jx/pkg/vault"
"github.com/Pallinder/go-randomdata"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io"
"github.com/ghodss/yaml"
"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/amazon"
"github.com/jenkins-x/jx/pkg/cloud/aks"
"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"
"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
}
// 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
GitSecretsFile = "gitSecrets.yaml"
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)
},
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())
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 Chart Museum")
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")
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 {
originalGitUsername := options.GitRepositoryOptions.Username
originalGitServer := options.GitRepositoryOptions.ServerURL
originalGitToken := options.GitRepositoryOptions.ApiToken
client, originalNs, err := options.KubeClient()
if err != nil {
return errors.Wrap(err, "failed to create the kube client")
}
options.KubeClientCached = client
ns := options.Flags.Namespace
if ns == "" {
ns = originalNs
}
options.SetDevNamespace(ns)
// lets avoid changing the environments in k8s if GitOps mode...
gitOpsDir := ""
gitOpsEnvDir := ""
if options.Flags.GitOpsMode {
// lets disable loading of Secrets from the jx namespace
options.SkipAuthSecretsMerge = true
options.Flags.DisableSetKubeContext = true
var err error
if options.Flags.Dir == "" {
options.Flags.Dir, err = os.Getwd()
if err != nil {
return err
}
}
gitOpsDir = filepath.Join(options.Flags.Dir, "jenkins-x-dev-environment")
gitOpsEnvDir = filepath.Join(gitOpsDir, "env")
templatesDir := filepath.Join(gitOpsEnvDir, "templates")
err = os.MkdirAll(templatesDir, util.DefaultWritePermissions)
if err != nil {
return errors.Wrapf(err, "Failed to make GitOps templates directory %s", templatesDir)
}
options.modifyDevEnvironmentFn = func(callback func(env *v1.Environment) error) error {
defaultEnv := kube.CreateDefaultDevEnvironment(ns)
_, err := gitOpsModifyEnvironment(templatesDir, kube.LabelValueDevEnvironment, defaultEnv, callback)
return err
}
options.modifyEnvironmentFn = func(name string, callback func(env *v1.Environment) error) error {
defaultEnv := &v1.Environment{}
defaultEnv.Labels = map[string]string{}
_, err := gitOpsModifyEnvironment(templatesDir, name, defaultEnv, callback)
return err
}
options.InitOptions.modifyDevEnvironmentFn = options.modifyDevEnvironmentFn
options.modifyConfigMapCallback = func(name string, callback func(configMap *core_v1.ConfigMap) error) (*core_v1.ConfigMap, error) {
return gitOpsModifyConfigMap(templatesDir, name, nil, callback)
}
options.modifySecretCallback = func(name string, callback func(secret *core_v1.Secret) error) (*core_v1.Secret, error) {
return gitOpsModifySecret(templatesDir, name, nil, callback)
}
}
if options.Flags.Provider == EKS {
var deps []string
d := binaryShouldBeInstalled("eksctl")
if d != "" {
deps = append(deps, d)
}
d = binaryShouldBeInstalled("heptio-authenticator-aws")
if d != "" {
deps = append(deps, d)
}
err := options.installMissingDependencies(deps)
if err != nil {
log.Errorf("%v\nPlease fix the error or install manually then try again", err)
os.Exit(-1)
}
}
if options.Flags.Provider == AKS {
var deps []string
d := binaryShouldBeInstalled("az")
if d != "" {
deps = append(deps, d)
}
err := options.installMissingDependencies(deps)
if err != nil {
log.Errorf("%v\nPlease fix the error or install manually then try again", err)
os.Exit(-1)
}
}
initOpts := &options.InitOptions
helmBinary := initOpts.HelmBinary()
// configure the Helm binary
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, originalNs)
} 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)
}
}
}
dependencies := []string{}
if !initOpts.Flags.RemoteTiller && !initOpts.Flags.NoTiller {
binDir, err := util.JXBinLocation()
if err != nil {
return errors.Wrap(err, "reading jx bin location")
}
_, install, err := shouldInstallBinary("tiller")
if !install && err == nil {
confirm := &survey.Confirm{
Message: "Uninstalling existing tiller binary:",
Default: true,
}
flag := true
err = survey.AskOne(confirm, &flag, nil)
if err != nil || flag == false {
return errors.New("Existing tiller must be uninstalled first in order to use the jx in tiller less mode")
}
// Uninstall helm and tiller first to avoid using some older version
err = options.UninstallBinary(binDir, "tiller")
if err != nil {
return errors.Wrap(err, "uninstalling existing tiller binary")
}
}
_, install, err = shouldInstallBinary(helmBinary)
if !install && err == nil {
confirm := &survey.Confirm{
Message: "Uninstalling existing helm binary:",
Default: true,
}
flag := true
err = survey.AskOne(confirm, &flag, nil)
if err != nil || flag == false {
return errors.New("Existing helm must be uninstalled first in order to use the jx in tiller less mode")
}
// Uninstall helm and tiller first to avoid using some older version
err = options.UninstallBinary(binDir, helmBinary)
if err != nil {
return errors.Wrap(err, "uninstalling existing helm binary")
}
}
dependencies = append(dependencies, "tiller")
options.Helm().SetHost(tillerAddress())
}
dependencies = append(dependencies, helmBinary)
err = options.installRequirements(options.Flags.Provider, dependencies...)
if err != nil {
return errors.Wrap(err, "failed to install the platform requirements")
}
context := ""
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", ns)
if err != nil {
return errors.Wrapf(err, "failed to set the context '%s' in kube configuration", context)
}
}
options.Flags.Provider, err = options.GetCloudProvider(options.Flags.Provider)
if err != nil {
return errors.Wrapf(err, "failed to get the cloud provider '%s'", options.Flags.Provider)
}
initOpts.Flags.Provider = options.Flags.Provider
initOpts.Flags.Namespace = options.Flags.Namespace
exposeController := options.CreateEnvOptions.HelmValuesConfig.ExposeController
initOpts.Flags.Http = true
if exposeController != nil {
initOpts.Flags.Http = exposeController.Config.HTTP == "true"
}
initOpts.BatchMode = options.BatchMode
if options.Flags.Provider == AKS {
/**
* create a cluster admin role
*/
err = options.createClusterAdmin()
if err != nil {
return errors.Wrap(err, "failed to create the cluster admin")
}
log.Success("created role cluster-admin")
}
// lets ignore errors getting the current context in case we are running inside a pod
currentContext := ""
if !options.Flags.DisableSetKubeContext {
currentContext, err = options.getCommandOutput("", "kubectl", "config", "current-context")
if err != nil {
return errors.Wrap(err, "failed to get the current context")
}
}
isAwsProvider := options.Flags.Provider == AWS || options.Flags.Provider == EKS
if isAwsProvider {
err = options.ensureDefaultStorageClass(client, "gp2", "kubernetes.io/aws-ebs", "gp2")
if err != nil {
return err
}
}
if currentContext == "minikube" {
if options.Flags.Provider == "" {
options.Flags.Provider = MINIKUBE
}
if options.Flags.Domain == "" {
ip, err := options.getCommandOutput("", "minikube", "ip")
if err != nil {
return errors.Wrap(err, "failed to get the IP from Minikube")
}
options.Flags.Domain = ip + ".nip.io"
}
}
if initOpts.Flags.Domain == "" && options.Flags.Domain != "" {
initOpts.Flags.Domain = options.Flags.Domain
}
// lets default the helm domain
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 ecConfig.Domain == "" && options.Flags.Domain != "" {
ecConfig.Domain = options.Flags.Domain
log.Success("set exposeController Config Domain " + ecConfig.Domain + "\n")
}
if isOpenShiftProvider(options.Flags.Provider) {
ecConfig.Exposer = "Route"
}
}
callback := func(env *v1.Environment) error {
if env.Spec.TeamSettings.KubeProvider == "" {
env.Spec.TeamSettings.KubeProvider = options.Flags.Provider
log.Infof("Storing the kubernetes provider %s in the TeamSettings\n", env.Spec.TeamSettings.KubeProvider)
}
return nil
}
if !options.GitOpsMode {
apisClient, err := options.CreateApiExtensionsClient()
if err != nil {
return errors.Wrap(err, "failed to create the API extensions client")
}
kube.RegisterAllCRDs(apisClient)
if err != nil {
return err
}
}
err = options.ModifyDevEnvironment(callback)
if err != nil {
return err
}
if initOpts.Flags.NoTiller {
callback := func(env *v1.Environment) error {
env.Spec.TeamSettings.HelmTemplate = true
log.Info("Enabling helm template mode in the TeamSettings\n")
return nil
}
err = options.ModifyDevEnvironment(callback)
if err != nil {
return err
}
initOpts.helm = nil
}
if !initOpts.Flags.RemoteTiller && !initOpts.Flags.NoTiller {
err = restartLocalTiller()
if err != nil {
return err
}
initOpts.helm = options.helm
}
err = initOpts.Run()
if err != nil {
return errors.Wrap(err, "failed to initialize the jx")
}
if isOpenShiftProvider(options.Flags.Provider) {
err = options.enableOpenShiftSCC(ns)
if err != nil {
return errors.Wrap(err, "failed to enable the OpenShiftSCC")
}
}
if options.Flags.Provider == IKS {
/**
* Add the IBM chart repo for the Block Storage Driver
*/
err = options.addHelmBinaryRepoIfMissing(DEFAULT_IBMREPO_URL, "ibm")
if err != nil {
return errors.Wrap(err, "failed to add the IBM helm repo")
}
err = options.Helm().UpdateRepo()
if err != nil {
return errors.Wrap(err, "failed to update the helm repo")
}
err = options.Helm().UpgradeChart("ibm/ibmcloud-block-storage-plugin", "ibmcloud-block-storage-plugin",
"default", nil, true, nil, false, false, nil, nil, "")
if err != nil {
return errors.Wrap(err, "failed to install/upgrade the IBM Cloud Block Storage drivers")
}
err = options.changeDefaultStorageClass(client, "ibmc-block-bronze")
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
}
// TODO - we want to enable storing secrets in Vault for gitops. Reenable this once the feature is finished
//if options.Flags.GitOpsMode && !options.Flags.NoGitOpsVault || options.Flags.Vault {
if options.Flags.Vault {
// Install Vault Operator into the new env
err = InstallVaultOperator(&options.CommonOptions, "")
if err != nil {
return err
}
// Create a new System vault
cvo := &CreateVaultOptions{
CreateOptions: CreateOptions{
CommonOptions: options.CommonOptions,
},
UpgradeIngressOptions: UpgradeIngressOptions{
CreateOptions: CreateOptions{
CommonOptions: options.CommonOptions,
},
},
Namespace: ns,
}
vaultOperatorClient, err := cvo.Factory.CreateVaultOperatorClient()
if err != nil {
return err
}
if vault.FindVault(vaultOperatorClient, vault.SystemVaultName, ns) {
log.Infof("System vault named %s in namespace %s already exists\n",
util.ColorInfo(vault.SystemVaultName), util.ColorInfo(ns))
} else {
log.Info("Creating new system vault\n")
err = cvo.createVault(vaultOperatorClient, vault.SystemVaultName)
if err != nil {
return err
}
log.Infof("System vault created named %s in namespace %s.\n",
util.ColorInfo(vault.SystemVaultName), util.ColorInfo(ns))
}
options.Factory.UseVault(true)
}
// get secrets to use in helm install
secrets, err := options.getGitSecrets()
if err != nil {
return errors.Wrap(err, "failed to read the git secrets from configuration")
}
helmConfig := &options.CreateEnvOptions.HelmValuesConfig
if helmConfig.ExposeController.Config.Domain == "" {
helmConfig.ExposeController.Config.Domain = options.InitOptions.Flags.Domain
}
domain := helmConfig.ExposeController.Config.Domain
if domain != "" && addon.IsAddonEnabled("gitea") {
helmConfig.Jenkins.Servers.GetOrCreateFirstGitea().Url = "http://gitea-gitea." + ns + "." + domain
}
dockerRegistry, err := options.dockerRegistryValue()
if err != nil {
return errors.Wrap(err, "failed to get the docker registry value")
}
kubeConfig, _, err := options.Kube().LoadConfig()
if err != nil {
return err
}
if options.Flags.Provider == AKS {
/**
* Assign ACR role to AKS
*/
server := kube.CurrentServer(kubeConfig)
azureCLI := aks.NewAzureRunner()
resourceGroup, name, cluster, err := azureCLI.GetClusterClient(server)
if err != nil {
return errors.Wrap(err, "failed to get cluster from Azure")
}
registryID := ""
helmConfig.PipelineSecrets.DockerConfig, dockerRegistry, registryID, err = azureCLI.GetRegistry(resourceGroup, name, dockerRegistry)
if err != nil {
return errors.Wrap(err, "failed to get registry from Azure")
}
azureCLI.AssignRole(cluster, registryID)
log.Infof("Assign AKS %s a reader role for ACR %s\n", util.ColorInfo(server), util.ColorInfo(dockerRegistry))
}
if options.Flags.Provider == IKS {
dockerRegistry = iks.GetClusterRegistry(client)
helmConfig.PipelineSecrets.DockerConfig, err = iks.GetRegistryConfigJSON(dockerRegistry)
}
if dockerRegistry != "" {
if helmConfig.Jenkins.Servers.Global.EnvVars == nil {
helmConfig.Jenkins.Servers.Global.EnvVars = map[string]string{}
}
helmConfig.Jenkins.Servers.Global.EnvVars["DOCKER_REGISTRY"] = dockerRegistry
if isOpenShiftProvider(options.Flags.Provider) && dockerRegistry == "docker-registry.default.svc:5000" {
options.enableOpenShiftRegistryPermissions(ns, helmConfig, dockerRegistry)
}
}
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)
}
isProw := false
if options.Flags.GitOpsMode {
isProw = options.Flags.Prow
} else {
options.SetDevNamespace(ns)
isProw, err = options.isProw()
if err != nil {
return errors.Wrapf(err, "cannot work out if this is a prow based install in namespace %s", options.currentNamespace)
}
}
if isProw {
enableJenkins := false
helmConfig.Jenkins.Enabled = &enableJenkins
}
// lets add any GitHub Enterprise servers
gitAuthCfg, err := options.CreateGitAuthConfigService()
if err != nil {
return errors.Wrap(err, "failed to create the git auth config service")
}
err = options.addGitServersToJenkinsConfig(helmConfig, gitAuthCfg)
if err != nil {
return errors.Wrap(err, "failed to add the Git servers to Jenkins config")
}
username := originalGitUsername
if username == "" {
if os.Getenv(JX_GIT_USER) != "" {
username = os.Getenv(JX_GIT_USER)
}
}
if username != "" && originalGitToken != "" && originalGitServer != "" {
err = gitAuthCfg.SaveUserAuth(originalGitServer, &auth.UserAuth{
ApiToken: originalGitToken,
Username: username,
})
if err != nil {
return err
}
log.Infof("Saving Git token configuration for server %s and user name %s.\n",
util.ColorInfo(originalGitServer), util.ColorInfo(username))
}
config, err := helmConfig.String()
if err != nil {
return errors.Wrap(err, "failed to get the helm config")
}
// clone the environments repo
wrkDir, err := options.cloneJXCloudEnvironmentsRepo()
if err != nil {
return errors.Wrap(err, "failed to clone the jx cloud environments repo")
}
// 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 errors.Wrap(err, "failed to create a temporary config dir for Git credentials")
}
cloudEnvironmentValuesLocation := filepath.Join(makefileDir, CloudEnvValuesFile)
cloudEnvironmentSecretsLocation := filepath.Join(makefileDir, CloudEnvSecretsFile)
cloudEnvironmentSopsLocation := filepath.Join(makefileDir, CloudEnvSopsConfigFile)
sopsFileExists, err := util.FileExists(cloudEnvironmentSopsLocation)
if err != nil {
return errors.Wrap(err, "failed to look for "+cloudEnvironmentSopsLocation)
}
adminSecretsServiceInit := false
if sopsFileExists {
log.Infof("Attempting to decrypt secrets file %s\n", util.ColorInfo(cloudEnvironmentSecretsLocation))
// need to decrypt secrets now
err = options.Helm().DecryptSecrets(cloudEnvironmentSecretsLocation)
if err != nil {
return errors.Wrap(err, "failed to decrypt "+cloudEnvironmentSecretsLocation)
}
cloudEnvironmentSecretsDecryptedLocation := filepath.Join(makefileDir, CloudEnvSecretsFile+".dec")
decryptedSecretsFile, err := util.FileExists(cloudEnvironmentSecretsDecryptedLocation)
if err != nil {
return errors.Wrap(err, "failed to look for "+cloudEnvironmentSecretsDecryptedLocation)
}
if decryptedSecretsFile {
log.Infof("Successfully decrypted %s\n", util.ColorInfo(cloudEnvironmentSecretsDecryptedLocation))
cloudEnvironmentSecretsLocation = cloudEnvironmentSecretsDecryptedLocation
err = options.AdminSecretsService.NewAdminSecretsConfigFromSecret(cloudEnvironmentSecretsDecryptedLocation)
if err != nil {
return errors.Wrap(err, "failed to create the admin secret config service from the decrypted secrets file")
}
adminSecretsServiceInit = true
}
}
if !adminSecretsServiceInit {
err = options.AdminSecretsService.NewAdminSecretsConfig()
if err != nil {
return errors.Wrap(err, "failed to create the admin secret config service")
}
}
adminSecrets, err := options.AdminSecretsService.Secrets.String()
if err != nil {
return errors.Wrap(err, "failed to read the admin secrets")
}
secretsFileName := filepath.Join(dir, GitSecretsFile)
err = ioutil.WriteFile(secretsFileName, []byte(secrets), 0644)
if err != nil {
return errors.Wrap(err, "failed to write the git secrets in the secrets file")
}
adminSecretsFileName := filepath.Join(dir, AdminSecretsFile)
err = ioutil.WriteFile(adminSecretsFileName, []byte(adminSecrets), 0644)
if err != nil {
return errors.Wrap(err, "failed to write the admin secrets in the secrets file")
}
configFileName := filepath.Join(dir, ExtraValuesFile)
err = ioutil.WriteFile(configFileName, []byte(config), 0644)
if err != nil {
return errors.Wrap(err, "failed to write the config file")
}
data := make(map[string][]byte)
data[ExtraValuesFile] = []byte(config)
data[AdminSecretsFile] = []byte(adminSecrets)
data[GitSecretsFile] = []byte(secrets)
options.ModifySecret(JXInstallConfig, func(secret *core_v1.Secret) error {
secret.Data = data
return nil
})
log.Infof("Generated helm values %s\n", util.ColorInfo(configFileName))
timeout := options.Flags.Timeout
if timeout == "" {
timeout = defaultInstallTimeout
}
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
}
}
log.Infof("Installing Jenkins X platform helm chart from: %s\n", makefileDir)
options.Verbose = true
err = options.addHelmBinaryRepoIfMissing(DEFAULT_CHARTMUSEUM_URL, "jenkins-x")
if err != nil {
return errors.Wrap(err, "failed to add the jenkinx-x helm repo")
}
version := options.Flags.Version
if version == "" {
version, err = LoadVersionFromCloudEnvironmentsDir(wrkDir)
if err != nil {
return errors.Wrap(err, "failed to load version from cloud environments dir")
}
}
err = options.Helm().UpdateRepo()
if err != nil {
return errors.Wrap(err, "failed to update the helm repo")
}
valueFiles := []string{cloudEnvironmentValuesLocation, secretsFileName, adminSecretsFileName, configFileName, cloudEnvironmentSecretsLocation}
valueFiles, err = helm.AppendMyValues(valueFiles)
if err != nil {
return errors.Wrap(err, "failed to append the myvalues.yaml file")
}
options.currentNamespace = ns
if options.Flags.Prow {
// install Prow into the new env