forked from jenkins-x/jx
-
Notifications
You must be signed in to change notification settings - Fork 0
/
create_codeship.go
441 lines (373 loc) · 12.3 KB
/
create_codeship.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
package cmd
import (
"io"
"fmt"
"context"
"errors"
"github.com/Pallinder/go-randomdata"
"github.com/codeship/codeship-go"
"github.com/jenkins-x/jx/pkg/gits"
"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/jenkins-x/jx/pkg/version"
"github.com/spf13/cobra"
"gopkg.in/AlecAivazis/survey.v1"
"io/ioutil"
"os"
"path"
"strings"
)
type CreateCodeshipFlags struct {
OrganisationName string
ForkOrganisationGitRepo string
CodeshipUsername string
CodeshipPassword string
CodeshipOrganisation string
GitUser string
GitEmail string
GKEServiceAccount string
}
// CreateCodeshipOptions the options for the create spring command
type CreateCodeshipOptions struct {
CreateOptions
CreateTerraformOptions
CreateGkeServiceAccountOptions
Flags CreateCodeshipFlags
GitRepositoryOptions gits.GitRepositoryOptions
}
var (
createCodeshipExample = templates.Examples(`
jx create codeship
# to specify the org and service account via flags
jx create codeship -o org --gke-service-account <path>
`)
)
// NewCmdCreateCodeship creates a command object for the "create" command
func NewCmdCreateCodeship(f Factory, out io.Writer, errOut io.Writer) *cobra.Command {
options := &CreateCodeshipOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
CreateTerraformOptions: CreateTerraformOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
InstallOptions: createInstallOptions(f, out, errOut),
},
CreateGkeServiceAccountOptions: CreateGkeServiceAccountOptions{
CreateOptions: CreateOptions{
CommonOptions: CommonOptions{
Factory: f,
Out: out,
Err: errOut,
},
},
},
}
cmd := &cobra.Command{
Use: "codeship",
Short: "Creates a build on CodeShip to create/update JX clusters",
Example: createCodeshipExample,
Run: func(cmd *cobra.Command, args []string) {
options.Cmd = cmd
options.Args = args
err := options.Run()
CheckErr(err)
},
}
options.addCommonFlags(cmd)
options.addFlags(cmd)
options.CreateGkeServiceAccountOptions.addFlags(cmd)
options.CreateTerraformOptions.addFlags(cmd)
return cmd
}
func (options *CreateCodeshipOptions) addFlags(cmd *cobra.Command) {
// global flags
cmd.Flags().StringVarP(&options.Flags.OrganisationName, "organisation-name", "o", "", "The organisation name that will be used as the Git repo containing cluster details, the repo will be organisation-<org name>")
cmd.Flags().StringVarP(&options.Flags.CodeshipUsername, "codeship-username", "", "", "The username to login to Codeship with, this will not be stored anywhere")
cmd.Flags().StringVarP(&options.Flags.CodeshipPassword, "codeship-password", "", "", "The password to login to Codeship with, this will not be stored anywhere")
cmd.Flags().StringVarP(&options.Flags.CodeshipOrganisation, "codeship-organisation", "", "", "The Codeship organisation to use, this will not be stored anywhere")
cmd.Flags().StringVarP(&options.Flags.ForkOrganisationGitRepo, "fork-git-repo", "f", kube.DefaultOrganisationGitRepoURL, "The Git repository used as the fork when creating new Organisation git repos")
cmd.Flags().StringVarP(&options.Flags.GitUser, "git-user", "", "Codeship", "The name to use for any git commits")
cmd.Flags().StringVarP(&options.Flags.GitEmail, "git-email", "", "codeship@jenkins-x.io", "The email to use for any git commits")
cmd.Flags().StringVarP(&options.Flags.GKEServiceAccount, "gke-service-account", "", "", "The GKE service account to use")
}
func (o *CreateCodeshipOptions) validate() error {
if o.Flags.OrganisationName == "" {
return errors.New("No organisation has been set")
}
// TODO we should only do this if a GKE cluster has been specified
if o.Flags.GKEServiceAccount == "" {
return errors.New("No gke service account has been set")
}
return nil
}
// Run implements this command
func (o *CreateCodeshipOptions) Run() error {
if o.Flags.OrganisationName == "" {
o.Flags.OrganisationName = strings.ToLower(randomdata.SillyName())
}
// if gke-service-account is not set, create the service account
if o.Flags.GKEServiceAccount == "" {
gkeServiceAccountPath := path.Join(util.HomeDir(), fmt.Sprintf("%s.key.json", o.Flags.OrganisationName))
o.CreateGkeServiceAccountOptions.Flags.Name = o.Flags.OrganisationName
o.CreateGkeServiceAccountOptions.CommonOptions.BatchMode = o.CreateOptions.CommonOptions.BatchMode
err := o.CreateGkeServiceAccountOptions.Run()
if err != nil {
return err
}
o.Flags.GKEServiceAccount = gkeServiceAccountPath
}
err := o.validate()
if err != nil {
return err
}
if o.Flags.CodeshipUsername == "" {
prompt := &survey.Input{
Message: "Username for Codeship",
Help: "This will not be stored anywhere",
}
err := survey.AskOne(prompt, &o.Flags.CodeshipUsername, nil)
if err != nil {
return err
}
}
if o.Flags.CodeshipPassword == "" {
prompt := &survey.Password{
Message: "Password for Codeship",
Help: "This will not be stored anywhere",
}
err := survey.AskOne(prompt, &o.Flags.CodeshipPassword, nil)
if err != nil {
return err
}
}
if o.Flags.CodeshipOrganisation == "" {
prompt := &survey.Input{
Message: "Codeship organisation",
Help: "This will not be stored anywhere",
}
err := survey.AskOne(prompt, &o.Flags.CodeshipOrganisation, nil)
if err != nil {
return err
}
}
organisationDir, err := util.OrganisationsDir()
if err != nil {
return err
}
authConfigSvc, err := o.CreateGitAuthConfigService()
if err != nil {
return err
}
defaultRepoName := fmt.Sprintf("organisation-%s", o.Flags.OrganisationName)
details, err := gits.PickNewOrExistingGitRepository(o.Stdout(), o.BatchMode, authConfigSvc,
defaultRepoName, &o.GitRepositoryOptions, nil, nil, o.Git(), true)
if err != nil {
return err
}
org := details.Organisation
repoName := details.RepoName
owner := org
if owner == "" {
owner = details.User.Username
}
provider := details.GitProvider
repo, err := provider.GetRepository(owner, repoName)
remoteRepoExists := err == nil
var dir string
if !remoteRepoExists {
fmt.Fprintf(o.Stdout(), "Creating git repository %s/%s\n", util.ColorInfo(owner), util.ColorInfo(repoName))
repo, err = details.CreateRepository()
if err != nil {
return err
}
dir, err = util.CreateUniqueDirectory(organisationDir, details.RepoName, util.MaximumNewDirectoryAttempts)
if err != nil {
return err
}
err = o.Git().Clone(o.Flags.ForkOrganisationGitRepo, dir)
if err != nil {
return err
}
pushGitURL, err := o.Git().CreatePushURL(repo.CloneURL, details.User)
if err != nil {
return err
}
err = o.Git().AddRemote(dir, "upstream", o.Flags.ForkOrganisationGitRepo)
if err != nil {
return err
}
err = o.Git().SetRemoteURL(dir, "origin", pushGitURL)
if err != nil {
return err
}
} else {
fmt.Fprintf(o.Stdout(), "git repository %s/%s already exists\n", util.ColorInfo(owner), util.ColorInfo(repoName))
dir = path.Join(organisationDir, details.RepoName)
localDirExists, err := util.FileExists(dir)
if err != nil {
return err
}
if localDirExists {
// if remote repo does exist & local does exist, git pull the local repo
fmt.Fprintf(o.Stdout(), "local directory already exists\n")
err = o.Git().Pull(dir)
if err != nil {
return err
}
} else {
fmt.Fprintf(o.Stdout(), "cloning repository locally\n")
err = os.MkdirAll(dir, os.FileMode(0755))
if err != nil {
return err
}
// if remote repo does exist & local directory does not exist, clone locally
pushGitURL, err := o.Git().CreatePushURL(repo.CloneURL, details.User)
if err != nil {
return err
}
err = o.Git().Clone(pushGitURL, dir)
if err != nil {
return err
}
}
}
if !remoteRepoExists {
o.CreateTerraformOptions.CommonOptions.BatchMode = o.CreateOptions.CommonOptions.BatchMode
o.CreateTerraformOptions.Flags.OrganisationName = o.Flags.OrganisationName
o.CreateTerraformOptions.Flags.SkipTerraformApply = true
o.CreateTerraformOptions.Flags.GKEServiceAccount = o.Flags.GKEServiceAccount
o.CreateTerraformOptions.Flags.LocalOrganisationRepository = dir
err = o.CreateTerraformOptions.Run()
if err != nil {
return err
}
}
clusterDir := path.Join(dir, "clusters")
clusters, err := findClusters(clusterDir)
if err != nil {
return err
}
auth := codeship.NewBasicAuth(o.Flags.CodeshipUsername, o.Flags.CodeshipPassword)
//client, err := codeship.New(auth, codeship.Verbose(true))
client, err := codeship.New(auth)
if err != nil {
return err
}
ctx := context.Background()
csOrg, err := client.Organization(ctx, o.Flags.CodeshipOrganisation)
if err != nil {
return err
}
_, uuid, err := ProjectExists(ctx, csOrg, o.Flags.CodeshipOrganisation, repoName)
b, err := ioutil.ReadFile(o.Flags.GKEServiceAccount)
if err != nil {
return err
}
serviceAccount := string(b)
if uuid == "" {
//m := make(map[string]interface{})
//m["type"] = "script_deployment"
//m["commands"] = []string{"./build.sh"}
createProjectRequest := codeship.ProjectCreateRequest{
Type: codeship.ProjectTypeBasic,
RepositoryURL: fmt.Sprintf("git@github.com:%s/%s", owner, repoName),
SetupCommands: []string{"./build.sh"},
EnvironmentVariables: []codeship.EnvironmentVariable{
{Name: "GKE_SA_JSON", Value: serviceAccount},
{Name: "ORG", Value: o.Flags.OrganisationName},
{Name: "GIT_USERNAME", Value: details.User.Username},
{Name: "GIT_API_TOKEN", Value: details.User.ApiToken},
{Name: "JX_VERSION", Value: jxVersion()},
{Name: "GIT_USER", Value: o.Flags.GitUser},
{Name: "GIT_EMAIL", Value: o.Flags.GitEmail},
{Name: "BUILD_NUMBER", Value: "1"},
{Name: "ENVIRONMENTS", Value: strings.Join(clusters, ",")},
},
//DeploymentPipelines: []codeship.DeploymentPipeline{
// {
// Branch: codeship.DeploymentBranch{ BranchName: "master", MatchMode: "exact"},
// Config: m,
// Position: 1,
// },
//} ,
}
project, _, err := csOrg.CreateProject(ctx, createProjectRequest)
if err != nil {
return fmt.Errorf("failed to create project, check CodeShip is configured to authenticate against your git provider https://app.codeship.com/authentications. error: %v", err)
}
uuid = project.UUID
log.Infof("Created Project %s\n", util.ColorInfo(project.Name))
} else {
updateProjectRequest := codeship.ProjectUpdateRequest{
Type: codeship.ProjectTypeBasic,
SetupCommands: []string{"./build.sh"},
EnvironmentVariables: []codeship.EnvironmentVariable{
{Name: "GKE_SA_JSON", Value: serviceAccount},
{Name: "ORG", Value: o.Flags.OrganisationName},
{Name: "GIT_USERNAME", Value: details.User.Username},
{Name: "GIT_API_TOKEN", Value: details.User.ApiToken},
{Name: "JX_VERSION", Value: jxVersion()},
{Name: "GIT_USER", Value: o.Flags.GitUser},
{Name: "GIT_EMAIL", Value: o.Flags.GitEmail},
{Name: "BUILD_NUMBER", Value: "1"},
{Name: "ENVIRONMENTS", Value: strings.Join(clusters, ",")},
},
}
project, _, err := csOrg.UpdateProject(ctx, uuid, updateProjectRequest)
if err != nil {
return err
}
log.Infof("Updated Project %s\n", util.ColorInfo(project.Name))
}
log.Infof("Triggering build for %s\n", util.ColorInfo(uuid))
_, _, err = csOrg.CreateBuild(ctx, uuid, "heads/master", "")
if err != nil {
return err
}
return nil
}
func ProjectExists(ctx context.Context, org *codeship.Organization, codeshipOrg string, codeshipRepo string) (bool, string, error) {
projects, _, err := org.ListProjects(ctx)
if err != nil {
return false, "", err
}
projectName := fmt.Sprintf("%s/%s", codeshipOrg, codeshipRepo)
for _, p := range projects.Projects {
if p.Name == projectName {
log.Infof("Project %s already exists\n", util.ColorInfo(p.Name))
return true, p.UUID, nil
}
}
return false, "", nil
}
func jxVersion() string {
if version.Version == "1.0.1" {
return "1.3.143"
}
return version.Version
}
func findClusters(path string) ([]string, error) {
var clusters = []string{}
files, err := ioutil.ReadDir(path)
if err != nil {
return clusters, err
}
for _, f := range files {
if f.IsDir() {
clusters = append(clusters, fmt.Sprintf("%s=gke", f.Name()))
}
}
return clusters, nil
}