-
Notifications
You must be signed in to change notification settings - Fork 41
/
Jenkinsfile
369 lines (328 loc) · 16.9 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
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
/* Import Pipeline Global Library.
* Implemented in src/com/redhat/ and vars/
*/
@Library('Utils') _
/* The path, relative to the root of the repo (where this Jenkinsfile is),
* where the file that contains the version tag (e.g. 1.0) resides.
*/
final APP_VERSION_FILE = 'app/VERSION'
pipeline {
agent any
stages {
/** Create Credentials
*
* Create a Jenkins Credential from OpenShift Secret
* In this case the OpenShift service tokens for the other
* environments.
*/
stage('Create Credentials') {
steps {
/* This method is implemented in vars/syncOpenShiftSecret.groovy */
syncOpenShiftSecret params.STAGE_SECRET_NAME
}
}
/** Dev - MochaJS Test
*
* Using agent labeled `nodejs` which is defined in the Kubernetes Jenkins plugin will
* launch a nodejs pod to run the steps section actions.
*/
stage('Dev - MochaJS Test') {
agent {
label 'nodejs'
}
steps {
dir('app') {
sh 'npm install'
sh 'npm test'
}
}
}
/** Dev - OpenShift Template
*
* This stage applies the template that is available in the project repository.
* Processes the template using parameters defined in the Jenkins Job
* And finally applies the objects returned from processing
*/
stage('Dev - OpenShift Template') {
steps {
script {
def openShiftApplyArgs = ""
updateBuildConfig = false
/* Read the version but make sure there is not any characters we do not expect */
if (! fileExists(APP_VERSION_FILE)) {
error("Application version tracking file ${APP_VERSION_FILE} does not exist!")
return
}
env.VERSION = readFile(APP_VERSION_FILE).trim()
env.TAG = "${env.VERSION}-${env.BUILD_NUMBER}"
openshift.withCluster(params.DEV_URI) {
openshift.withProject(params.DEV_PROJECT) {
/* If either there is a change in the OpenShift template
* or there is no template object available in OpenShift
* create the template.
*
* Otherwise use the `oc` command option `--dry-run` which
* will still allow the return of the objects from the openshift.apply()
* method but not actually apply those objects.
*
* findFileChanges method is implemented in vars/findFileChanges.groovy
*/
if (findFileChanges(params.APP_TEMPLATE_PATH)
|| !openshift.selector("template/${params.APP_DC_NAME}").exists()) {
/* Apply the template object from JSON file */
openshift.apply(readFile(params.APP_TEMPLATE_PATH))
echo ">>>>> OpenShift Template Changed <<<<<"
} else {
openShiftApplyArgs = "--dry-run"
updateBuildConfig = true
echo ">>>>> OpenShift Template Unchanged <<<<<"
}
/* Process the template and return the Map of the result */
def model = openshift.process(params.IMAGE_STREAM_NAME,
"-l app=${params.APP_DC_NAME}",
"-p",
"TAG=${env.TAG}",
"IMAGESTREAM_TAG=${params.IMAGE_STREAM_LATEST_TAG}",
"REGISTRY_PROJECT=${params.REGISTRY_PROJECT}",
"REGISTRY=${params.REGISTRY_URI}")
/* If the project's secret exists it must be removed at least in
* the case of using a database along with an application.
*
* The section below confirms if the secret exists and if so removes the
* item from the collection.
*
* Issue: When using a template with generated values each process of that
* template will change the generated values. If a DeploymentConfig is not
* redeployed those changes will not be propagated.
*/
if (openshift.selector("secret/${params.APP_DC_NAME}").exists()) {
def count = 0
for (item in model) {
if (item.kind == 'Secret') {
model.remove(count)
}
count++
}
}
echo ">>>>> Enter OpenShift Apply Template Model <<<<<"
createdObjects = openshift.apply(model, openShiftApplyArgs)
echo ">>>>> Exit OpenShift Apply Template Model <<<<<"
}
}
}
}
}
/** Dev - Build Image
*
* This stage executes the BuildConfig with `oc start-build` building the application container image.
*/
stage('Dev - Build Image') {
steps {
script {
openshift.withCluster(params.DEV_URI) {
openshift.withProject(params.DEV_PROJECT) {
/* Select only BuildConfig from the objects that were created from the template
* process and apply
*/
def buildConfig = openshift.selector("buildconfig/${params.APP_DC_NAME}").object()
buildConfigs = createdObjects.narrow('bc')
imageName = "${params.REGISTRY_URI}/${params.REGISTRY_PROJECT}/" +
"${params.IMAGE_STREAM_NAME}:${env.TAG}"
if (updateBuildConfig) {
echo ">>>>> Enter OpenShift Apply BuildConfig <<<<<"
buildConfig.spec.output.to.name = imageName
openshift.apply(buildConfig)
openshift.raw("annotate", "buildconfig/${params.APP_DC_NAME}",
"kubectl.kubernetes.io/last-applied-configuration-")
echo ">>>>> Exit OpenShift Apply BuildConfig <<<<<"
}
def build = null
def buildErrorLog = "Build Error"
/* Execute a `oc start-build` for each available BuildConfig */
buildConfigs.withEach {
build = it.startBuild()
}
timeout(10) {
build.untilEach {
/* Wait until a build object is complete */
echo ">>>>> Enter Build Status Check <<<<<"
def phase = it.object().status.phase
echo ">>>>> Exit Build Status Check - Phase: ${phase} <<<<<"
if (phase == "Complete") {
return true
} else if (phase == "Failed") {
currentBuild.result = 'FAILURE'
buildErrorLog = it.logs().actions[0].err
return true
} else {
return false
}
}
}
/* If the currentBuild result is failure print the OpenShift Build error log
* and exit the job.
*/
if (currentBuild.result == 'FAILURE') {
error(buildErrorLog)
return
}
openshift.tag("--source=docker",
"${imageName}",
"${openshift.project()}/${params.IMAGE_STREAM_NAME}:${params.IMAGE_STREAM_LATEST_TAG}")
/* Resolves issue with an ImageStream that won't initially
* import a tag
*
* Select the ImageStream and check if that tags list contains a
* map with a key 'conditions'. If conditions exist run `oc import-image`.
* This will perform the initial pull of the the ImageStreamTag.
*
* After the initial run confirm that conditions does not exist and exit the
* loop.
*/
def importImage = false
def reCheck = false
timeout(10) {
createdObjects.narrow('is').untilEach {
echo ">>>>> Enter ImageStream Check <<<<<"
echo ">>>>> importImage: ${importImage} reCheck: ${reCheck} <<<<<"
if (importImage) {
reCheck = true
}
for (item in it.object().status.tags) {
if (item.containsKey('conditions')) {
importImage = true
reCheck = false
openshift.raw("import-image ${it.name()}")
sleep(30)
}
}
echo ">>>>> Exit ImageStream Check <<<<<"
echo ">>>>> importImage: ${importImage} reCheck: ${reCheck} <<<<<"
/* NXOR - if importImage and reCheck are both true or false
* return true, else return false
*
* Multiple scenarios (importImage, reCheck):
* - No import required (false, false)
* - Imported image but needs to be rechecked (true, false)
* - This should never happen (false, true)
* - Imported image and checked (true, true)
*/
return (!(importImage ^ reCheck))
}
}
/* If we need the URL to the application that we are deploying */
env.DEV_ROUTE = createdObjects.narrow('route').object().spec.host
echo "Application URL: ${env.DEV_ROUTE}"
}
}
}
}
}
/** Dev - Rollout Latest
*
* This stage rolls out the OpenShift DeploymentConfig defining the application.
* It will wait until the rollout completes or fails.
*/
stage('Dev - Rollout Latest') {
steps {
script {
openshift.withCluster(params.DEV_URI) {
openshift.withProject(params.DEV_PROJECT) {
/* Select the OpenShift DeploymentConfig object
* Initiate a `oc rollout latest` command
* Watch the status until the rollout is complete using the `oc`
* option `-w` to watch
*/
def result = null
deploymentConfig = openshift.selector("dc", params.APP_DC_NAME)
deploymentConfig.rollout().latest()
timeout(10) {
result = deploymentConfig.rollout().status("-w")
}
if (result.status != 0) {
error(result.err)
}
}
}
}
}
}
/** Stage - OpenShift Template
*
* This is generally duplicated from the Dev - OpenShift Template
* See inline documentation above.
*/
stage('Stage - OpenShift Template') {
environment {
STAGE = credentials("${params.STAGE_SECRET_NAME}")
}
steps {
script {
openshift.withCluster(params.STAGE_URI, env.STAGE_PSW) {
openshift.withProject(params.STAGE_PROJECT) {
def openShiftApplyArgs = ""
if (findFileChanges(params.APP_TEMPLATE_PATH)
|| !openshift.selector("template/${params.APP_DC_NAME}").exists()) {
openshift.apply(readFile(params.APP_TEMPLATE_PATH))
} else {
openShiftApplyArgs = "--dry-run"
openshift.tag("--source=docker",
"${imageName}",
"${openshift.project()}/${params.IMAGE_STREAM_NAME}:${params.IMAGE_STREAM_LATEST_TAG}")
}
def model = openshift.process(params.IMAGE_STREAM_NAME,
"-l app=${params.APP_DC_NAME}",
"-p",
"TAG=${env.TAG}",
"IMAGESTREAM_TAG=${params.IMAGE_STREAM_LATEST_TAG}",
"REGISTRY_PROJECT=${params.REGISTRY_PROJECT}",
"REGISTRY=${params.REGISTRY_URI}")
if (openshift.selector("secret/${params.APP_DC_NAME}").exists()) {
def count = 0
for (item in model) {
if (item.kind == 'Secret') {
model.remove(count)
}
count++
}
}
createdObjects = openshift.apply(model, openShiftApplyArgs)
/* The stage environment does not need OpenShift BuildConfig objects */
if (createdObjects.narrow('bc').exists()) {
createdObjects.narrow('bc').delete()
}
}
}
}
}
}
/** Stage - Rollout
*
* This is generally duplicated from the Dev - Rollout
* See inline documentation above.
*/
stage('Stage - Rollout') {
environment {
STAGE = credentials("${params.STAGE_SECRET_NAME}")
}
steps {
script {
openshift.withCluster(params.STAGE_URI, env.STAGE_PSW) {
openshift.withProject(params.STAGE_PROJECT) {
def result = null
deploymentConfig = openshift.selector("dc", params.APP_DC_NAME)
deploymentConfig.rollout().latest()
timeout(10) {
result = deploymentConfig.rollout().status("-w")
}
if (result.status != 0) {
error(result.err)
}
}
}
}
}
}
}
}
// vim: ft=groovy