-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJenkinsfile
263 lines (236 loc) · 11.6 KB
/
Jenkinsfile
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
appName = "hello-world"
// When using SSH repo URLs (e.g. for private repos), you need to uncomment and set the following variable.
// You also need to set the SSH URL and the sourceSecret in "BuildConfig > spec > source" definition in abar.yml.
//gitRemoteUrl = "[email protected]:abarcloud/hello-world.git"
def deleteEverything(instanceName) {
openshift.withCluster() {
openshift.withProject() {
// Except imagestream
openshift.selector("replicationcontroller,deployment,build,pod,buildconfig,deploymentconfig,service,route", [app: instanceName]).delete("--ignore-not-found")
}
}
}
pipeline {
options {
timeout(time: 60, unit: 'MINUTES')
disableConcurrentBuilds()
}
triggers {
issueCommentTrigger('.*/test.*')
}
agent any
stages {
stage('prepare') {
steps {
script {
//
// Determine build target name, instance name, image stream name and tag
//
if (env.CHANGE_ID) {
buildTarget = "pr-${env.CHANGE_ID}"
imageStreamName = "${appName}-contrib"
imageStreamTag = "pr-${env.CHANGE_ID}"
} else if (env.TAG_NAME) {
buildTarget = "release"
imageStreamName = "${appName}-release"
imageStreamTag = env.TAG_NAME
} else if (env.BRANCH_NAME) {
buildTarget = "branch-${env.BRANCH_NAME}".replaceAll(/(\\/|_|-)+/,"-")
imageStreamName = "${appName}-${buildTarget}"
imageStreamTag = "build-${env.BUILD_ID}"
} else {
error("No branch nor pull-request ID nor git tag was provided")
}
instanceName = "${appName}-${buildTarget}"
//
// Post pending commit statuses to GitHub
//
githubNotify status: "PENDING", context: "build", description: 'Starting pipeline'
githubNotify status: "PENDING", context: "preview", description: 'Waiting for successful build', targetUrl: " "
//
// Find useful git info in various steps
//
gitCommit = sh(returnStdout: true, script: "git rev-parse HEAD").trim()
gitShortCommit = sh(returnStdout: true, script: "git log -n 1 --pretty=format:'%h'").trim()
gitMessage = sh(returnStdout: true, script: "git log -n 1 --pretty=format:'%B'").trim()
if (!getBinding().hasVariable("gitRemoteUrl")) {
gitRemoteUrl = sh(returnStdout: true, script: "git config --get remote.origin.url").trim()
}
// Print variables
echo ("buildTarget = ${buildTarget}")
echo ("instanceName = ${instanceName}")
echo ("imageStreamName = ${imageStreamName}")
echo ("imageStreamTag = ${imageStreamTag}")
echo ("gitCommit = ${gitCommit}")
echo ("gitShortCommit = ${gitShortCommit}")
echo ("gitRemoteUrl = ${gitRemoteUrl}")
// Initialize some variables
previewResolution = ""
needsPreview = gitMessage.contains("[preview]")
openshift.withCluster() {
openshift.withProject() {
// Create imagestream if not exist yet
if (openshift.selector("imagestream", imageStreamName).count() == 0) {
openshift.create([
"kind": "ImageStream",
"metadata": [
"name": "${imageStreamName}"
]
])
}
echo "Building, testing and deploying for ${imageStreamName}:${imageStreamTag} in project ${openshift.project()}"
}
}
}
}
}
stage('cleanup') {
steps {
githubNotify status: "PENDING", context: "build", description: 'Cleaning up old resources'
deleteEverything(instanceName)
}
}
// Create a new app stack to fully build, deploy and serve this branch
stage('create') {
steps {
githubNotify status: "PENDING", context: "build", description: 'Creating new resources'
script {
openshift.withCluster() {
openshift.withProject() {
openshift.newApp(
"-f", "${pwd()}/abar.yml",
"-p", "NAME=${instanceName}",
"-p", "ROUTE_PREFIX=temp-${gitShortCommit}-${instanceName}",
"-p", "APP_GIT_ADDRESS=${gitRemoteUrl}",
"-p", "IMAGESTREAM_NAME=${imageStreamName}",
"-p", "IMAGESTREAM_TAG=${imageStreamTag}",
"-p", "IMAGESTREAM_NAMESPACE=${openshift.project()}"
)
// Set a custom env variable on DeploymentConfig for preview instances
openshift.raw("env dc/${instanceName} DEPLOYMENT_ENV=${imageStreamName}:${imageStreamTag}")
}
}
}
}
}
// Build on a new BuildConfig which also runs tests via spec.postCommit.script
stage('build') {
steps {
githubNotify status: "PENDING", context: "build", description: 'Running build and tests'
script {
if (env.CHANGE_ID) {
refSpec = "refs/pull/${env.CHANGE_ID}/head"
} else {
refSpec = gitCommit
}
}
echo ("Building based on refSpec = ${refSpec}")
script {
openshift.withCluster() {
openshift.withProject() {
openshiftBuild(bldCfg: instanceName, commitID: refSpec, showBuildLogs: 'true', waitTime: '30', waitUnit: 'min')
def builds = openshift.selector("bc", instanceName).related('builds')
builds.untilEach(1) {
return (it.object().status.phase == "Complete")
}
}
}
}
githubNotify status: "SUCCESS", context: "build", description: 'Successful build and tests'
}
}
// Deploy a preview instance for this branch/PR/tag
stage('deploy') {
when {
expression { needsPreview }
}
steps {
githubNotify status: "PENDING", context: "preview", description: 'Deploying preview', targetUrl: " "
script {
openshift.withCluster() {
openshift.withProject() {
def rm = openshift.selector("dc", instanceName).rollout().latest()
openshift.selector("dc", instanceName).related('pods').untilEach(1) {
return (it.object().status.phase == "Running")
}
previewRouteHost = openshift.selector("route", instanceName).object().spec.host
echo "Preview is live on: http://${previewRouteHost}"
if (env.CHANGE_ID) {
def found = false
def commentBody = "Live preview of build *[${imageStreamName}:${imageStreamTag}](${env.RUN_DISPLAY_URL}) @ ${gitShortCommit}* is available on: http://${previewRouteHost}"
for (comment in pullRequest.comments) {
if (comment.body.contains("Live preview of build")) {
pullRequest.editComment(comment.id, commentBody)
found = true
break
}
}
if (!found) {
prComment = pullRequest.comment(commentBody)
echo "prComment.id = ${prComment.id}"
}
}
}
}
}
githubNotify status: "SUCCESS", context: "preview", description: "Preview is online on http://${previewRouteHost}", targetUrl: "http://${previewRouteHost}"
}
}
stage('teardown') {
when {
expression { needsPreview }
}
steps {
script {
echo "Preview is available on: http://${previewRouteHost}"
previewResolution = input message: "Finished viewing changes?",
parameters: [choice(name: 'previewResolution', choices: 'Teardown preview instance\nKeep preview online', description: 'Should I destroy the preview instance when this build is finished?')]
}
}
}
}
post {
always {
script {
// In cases where the error is not explanatory in Jenkins UI,
// uncomment this section to prevent BuildConfig from being destroyed when the pipeline finishes.
// You can "Proceed" this input from Jenkins job's logs.
//
//if (currentBuild.result == "FAILURE") {
// input message: "Finished investigating failure?"
//}
if (previewResolution == "" || previewResolution.contains("Teardown")) {
deleteEverything(instanceName)
}
if (!needsPreview) {
githubNotify status: "SUCCESS", context: "preview", description: "Skipped preview since it was not requested", targetUrl: " "
}
}
}
success {
script {
// Tag successfully built image as latest (except for PRs).
// This is most useful for myapp-release and myapp-branch-master image streams.
// For example your staging app can use myapp-branch-master:latest
if (env.CHANGE_ID == null) {
openshiftTag(
srcStream: imageStreamName,
srcTag: imageStreamTag,
destStream: imageStreamName,
destTag: "latest"
)
}
}
}
failure {
script {
githubNotify status: "FAILURE", context: "build", description: "Pipeline failed!"
if (needsPreview) {
githubNotify status: "FAILURE", context: "preview", description: "Pipeline failed!", targetUrl: " "
} else {
githubNotify status: "SUCCESS", context: "preview", description: "Skipped preview since it was not requested", targetUrl: " "
}
}
}
}
} // pipeline