forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_env.go
220 lines (192 loc) · 7.86 KB
/
create_env.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
package cmd
import (
"io"
"github.com/spf13/cobra"
"fmt"
"github.com/jenkins-x/jx/pkg/apis/jenkins.io/v1"
"github.com/jenkins-x/jx/pkg/config"
"github.com/jenkins-x/jx/pkg/gits"
"github.com/jenkins-x/jx/pkg/jenkins"
"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/prow"
"github.com/jenkins-x/jx/pkg/util"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
var (
env_description = `
An Environment maps to a kubernetes cluster and namespace and is a place that your team's applications can be promoted to via Continous Delivery.
You can optionally use GitOps to manage the configuration of an Environment by storing all configuration in a git repository and then only changing it via Pull Requests and CI/CD.
For more documentation on Environments see: [https://jenkins-x.io/about/features/#environments](https://jenkins-x.io/about/features/#environments)
`
create_env_long = templates.LongDesc(`
Creates a new Environment
` + env_description + `
`)
create_env_example = templates.Examples(`
# Create a new Environment, prompting for the required data
jx create env
# Creates a new Environment passing in the required data on the command line
jx create env -n prod -l Production --no-gitops --namespace my-prod
`)
)
// CreateEnvOptions the options for the create spring command
type CreateEnvOptions struct {
CreateOptions
Options v1.Environment
HelmValuesConfig config.HelmValuesConfig
PromotionStrategy string
NoGitOps bool
Prow bool
ForkEnvironmentGitRepo string
EnvJobCredentials string
GitRepositoryOptions gits.GitRepositoryOptions
Prefix string
BranchPattern string
}
// NewCmdCreateEnv creates a command object for the "create" command
func NewCmdCreateEnv(f Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := &CreateEnvOptions{
HelmValuesConfig: config.HelmValuesConfig{
ExposeController: &config.ExposeController{},
},
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
}
cmd := &cobra.Command{
Use: "environment",
Short: "Create a new Environment which is used to promote your Team's Applications via Continuous Delivery",
Aliases: []string{"env"},
Long: create_env_long,
Example: create_env_example,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
//addCreateAppFlags(cmd, &options.CreateOptions)
cmd.Flags().StringVarP(&options.Options.Name, kube.OptionName, "n", "", "The Environment resource name. Must follow the kubernetes name conventions like Services, Namespaces")
cmd.Flags().StringVarP(&options.Options.Spec.Label, "label", "l", "", "The Environment label which is a descriptive string like 'Production' or 'Staging'")
cmd.Flags().StringVarP(&options.Options.Spec.Namespace, kube.OptionNamespace, "s", "", "The Kubernetes namespace for the Environment")
cmd.Flags().StringVarP(&options.Options.Spec.Cluster, "cluster", "c", "", "The Kubernetes cluster for the Environment. If blank and a namespace is specified assumes the current cluster")
cmd.Flags().StringVarP(&options.Options.Spec.Source.URL, "git-url", "g", "", "The Git clone URL for the source code for GitOps based Environments")
cmd.Flags().StringVarP(&options.Options.Spec.Source.Ref, "git-ref", "r", "", "The Git repo reference for the source code for GitOps based Environments")
cmd.Flags().Int32VarP(&options.Options.Spec.Order, "order", "o", 100, "The order weighting of the Environment so that they can be sorted by this order before name")
cmd.Flags().StringVarP(&options.Prefix, "prefix", "", "jx", "Environment repo prefix, your git repo will be of the form 'environment-$prefix-$envName'")
cmd.Flags().StringVarP(&options.PromotionStrategy, "promotion", "p", "", "The promotion strategy")
cmd.Flags().StringVarP(&options.ForkEnvironmentGitRepo, "fork-git-repo", "f", kube.DefaultEnvironmentGitRepoURL, "The Git repository used as the fork when creating new Environment git repos")
cmd.Flags().StringVarP(&options.EnvJobCredentials, "env-job-credentials", "", "", "The Jenkins credentials used by the GitOps Job for this environment")
cmd.Flags().StringVarP(&options.BranchPattern, "branches", "", "", "The branch pattern for branches to trigger CI/CD pipelines on the enivronment git repository")
cmd.Flags().BoolVarP(&options.NoGitOps, "no-gitops", "x", false, "Disables the use of GitOps on the environment so that promotion is implemented by directly modifying the resources via helm instead of using a git repository")
cmd.Flags().BoolVarP(&options.Prow, "prow", "", false, "Install and use Prow for environment promotion")
addGitRepoOptionsArguments(cmd, &options.GitRepositoryOptions)
options.HelmValuesConfig.AddExposeControllerValues(cmd, false)
return cmd
}
// Run implements the command
func (o *CreateEnvOptions) Run() error {
args := o.Args
if len(args) > 0 && o.Options.Name == "" {
o.Options.Name = args[0]
}
jxClient, currentNs, err := o.JXClientAndDevNamespace()
if err != nil {
return err
}
kubeClient, _, err := o.KubeClient()
if err != nil {
return err
}
apisClient, err := o.CreateApiExtensionsClient()
if err != nil {
return err
}
kube.RegisterEnvironmentCRD(apisClient)
ns, _, err := kube.GetDevNamespace(kubeClient, currentNs)
if err != nil {
return err
}
envDir, err := util.EnvironmentsDir()
if err != nil {
return err
}
authConfigSvc, err := o.CreateGitAuthConfigService()
if err != nil {
return err
}
devEnv, err := kube.EnsureDevEnvironmentSetup(jxClient, ns)
if err != nil {
return err
}
if o.Prow {
devEnv.Spec.TeamSettings.PromotionEngine = v1.PromotionEngineProw
devEnv, err = jxClient.JenkinsV1().Environments(ns).Update(devEnv)
if err != nil {
return err
}
}
env := v1.Environment{}
o.Options.Spec.PromotionStrategy = v1.PromotionStrategyType(o.PromotionStrategy)
gitProvider, err := kube.CreateEnvironmentSurvey(o.Out, o.BatchMode, authConfigSvc, devEnv, &env, &o.Options, o.ForkEnvironmentGitRepo, ns,
jxClient, kubeClient, envDir, &o.GitRepositoryOptions, o.HelmValuesConfig, o.Prefix, o.Git())
if err != nil {
return err
}
_, err = jxClient.JenkinsV1().Environments(ns).Create(&env)
if err != nil {
return err
}
log.Infof("Created environment %s\n", util.ColorInfo(env.Name))
err = kube.EnsureEnvironmentNamespaceSetup(kubeClient, jxClient, &env, ns)
if err != nil {
return err
}
gitURL := env.Spec.Source.URL
gitInfo, err := gits.ParseGitURL(gitURL)
if o.Prow {
repo := fmt.Sprintf("%s/environment-%s-%s", gitInfo.Organisation, o.Prefix, o.Options.Name)
err = prow.AddRepo(o.KubeClientCached, []string{repo}, devEnv.Spec.Namespace)
if err != nil {
return fmt.Errorf("failed to add repo %s to prow config in namespace %s: %v", repo, env.Spec.Namespace, err)
}
}
if gitURL != "" {
if gitProvider == nil {
p, err := o.gitProviderForURL(gitURL, "user name to create the git repository")
if err != nil {
return err
}
gitProvider = p
}
if o.Prow {
// register the webhook
baseURL, err := kube.GetServiceURLFromName(o.KubeClientCached, "hook", o.devNamespace)
if err != nil {
return err
}
webhookUrl := util.UrlJoin(baseURL, "hook")
hmacToken, err := o.KubeClientCached.CoreV1().Secrets(o.devNamespace).Get("hmac-token", metav1.GetOptions{})
if err != nil {
return err
}
webhook := &gits.GitWebHookArguments{
Owner: gitInfo.Organisation,
Repo: gitInfo,
URL: webhookUrl,
Secret: string(hmacToken.Data["hmac"]),
}
return gitProvider.CreateWebHook(webhook)
} else {
return o.ImportProject(gitURL, envDir, jenkins.DefaultJenkinsfile, o.BranchPattern, o.EnvJobCredentials, false, gitProvider, authConfigSvc, true, o.BatchMode)
}
}
return nil
}