-
Notifications
You must be signed in to change notification settings - Fork 4
/
jenkins-pipeline-execution
executable file
·455 lines (386 loc) · 11.8 KB
/
jenkins-pipeline-execution
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
### PIPELINE KEYPOINTS ### ****************************************************
# A user may choose to write a pipeline script locally
# or pull from an SCM source
### TRIGGERS ### ****************************************************
# Pull strategy
* Reaches out to see if changes in the code
# Push strategy
* Something else notifies Jenkins the code changed
# Triggers can be implemented in three ways
# General Configuration of the Project
# Scripted Pipeline
# Example: Building a Project
# after other projects are built
properties([
pipelineTriggers([
upstream(
threshold: hudson.model.Result.SUCCESS,
upstreamProjects: 'Job1'
)
])
])
# Example: Build periodically
properties([pipelineTriggers([cron('0 9 * * 1-5')])])
# Example: Github Hook Trigger for GitSCM polling
# Used to trigger a build when git push initiated
properties([pipelineTriggers([githubPush()])])
# Example: Poll SCM periodically
properties([pipelineTriggers([pollSCM('*/30 * * * *')])])
# Declarative Pipeline
# Example: Build periodically
triggers { cron(0 9 * * 1-5)
# Example: Poll SCM periodically
triggers { pollSCM(*/30 * * * *) }
# Example: Trigger builds remotely by
# accessing a specific URL for the given
# job on the Jenkins system
# Freestyle project
# Check "Github hook trigger for GITScm polling"
# Global config should have auth configured
# Under the settings of the repo, the webhook
# will show up once the project is created
### USER INPUT ### ****************************************************
# Prompt user with message
input 'Continue with the final stage?'
# Give the user a variety of choices
def choice = input message: '<message>',
parameters: [choice(choices: "choice1\nchoice2\nchoice3\nchoice4\n",
description: 'Choose one of the following options', name: 'Options')]
# Boolean
def answer = input message: '<message>',
parameters: [booleanParam(defaultValue: true,
description: 'Prerelease setting', name: 'prerelease')]
# Choosing a file to use with the pipeline
def selectedFile = input message: '<message>',
parameters: [file(description: 'Choose file to upload', name: 'local')]
# Multiline string
def lines = input message: '<message>',
parameters: [text(defaultValue: '''line 1
line 2
line 3''', description: '', name: 'Input Lines')]
# Script block (Used for allowing scripted pipeline syntax
# in declarative syntax language)
stage ('Input') {
steps {
script {
def resp = input message: '<message>',
parameters: [string(defaultValue: '',
description: 'Enter response 1',
name: 'RESPONSE1'), string(defaultValue: '',
description: 'Enter response 2', name: 'RESPONSE2')]
echo "${resp.RESPONSE1}"
}
echo "${resp.RESPONSE2}"
}
}
## Flow control options ##
# Use timeout (Limits amount of time your script spends waiting
# for an action to happen)
node {
def response
stage('input') {
timeout(time:10, unit:'SECONDS') {
response = input message: 'User',
parameters: [string(defaultValue: 'user1',
description: 'Enter Userid:', name: 'userid')]
}
echo "Username = " + response
}
}
# Exception handling with timeout
node {
def response
stage('input') {
try {
timeout(time:10, unit:'SECONDS') {
response = input message: 'User',
parameters: [string(defaultValue: 'user1',
description: 'Enter Userid:', name: 'userid')]
}
}
catch (err) {
currentBuild.result = "FAILED"
response = 'user1'
throw err
}
}
}
# Retrying the process
retry(<n>) { // processing }
# Sleeping (Delay step)
sleep time: 5, unit: 'MINUTES'
# Wait until something happens
timeout(time:15, unit:'SECONDS') {
waitUntil {
def ret = sh returnStatus: true,
script: 'test -e /home/jenkins2/marker.txt'
return (ret == 0)
}
}
# Stash and unstash
# Allows for saving and retreving files between
# nodes and/or stages in a pipeline
stages {
stage('Source') {
git branch: 'test', url: 'git@diyv:repos/gradle-greetings'
stash name: 'test-source', includes: 'build.gradle,src/test/'
}
...
stage ('Test') {
// execute required unit tests in parallel
parallel (
master: { node ('master') {
unstash 'test-sources'
sh '/opt/gradle-2.7/bin/gradle -D test.single=TestExample1 test'
}},
worker2: { node ('worker_node2') {
unstash 'test-sources'
sh '/opt/gradle-2.7/bin/gradle -D test.single=TestExample2 test'
}},
)
}
}
# Advanced error handling
def err = null
try {
// pipeline code
node ('node-name') {
stage ('first stage') {
...
} // end of last stage
}
}
catch (err) {
currentBuild.result = "FAILURE"
}
finally {
(currentBuild.result != "ABORTED"){
// Send email notifications for builds that failed
// or are unstable
}
}
# Post-processing
# Conditions:
# always: Always executes the steps in the block
# changed: Executed if current build different from previous build
# success: Executes if current build successful
# failure: Executes if current build failed
# unstable: Executes if current build unstable
}
} // end stages
post {
always {
echo "Build stage complete"
}
failure {
echo "Build failed"
mail body: 'build failed', subject: 'Build failed!',
to: 'devops@company.com'
}
success {
echo "Build succeeded"
mail body: 'build succeeded', subject: 'Build Succeeded',
to: 'devops@company.com'
}
}
} // end pipeline
# Sending an email
pipeline {
agent any
stages {
...
}
post {
always {
mail to: 'blob@gmail.org',
subject: "Status of pipeline: ${currentBuild.fullDisplayName}",
body: "${env.BUILD_URL} has result ${currentBuild.result}"
}
}
}
# SMTP server, default user email suffix, SMTP
# authentication defined in global settings
# Send email with attached logs
emailext attachLog: true, body:
"""<p>EXECUTED: Job <b>\'${env.JOB_NAME}:${env.BUILD_NUMBER})\'
</b></p><p>View console output at "<a href="${env.BUILD_URL}">
${env.JOB_NAME}:${env.BUILD_NUMBER}</a>"</p>
<p><i>(Build log is attached.)</i></p>""",
compressLog: true,
recipientProviders: [[$class: 'DevelopersRecipientProvider'],
[$class: 'RequesterRecipientProvider']],
replyTo: 'do-not-reply@company.com',
subject: "Status: ${currentBuild.result?:'SUCCESS'} -
Job \'${env.JOB_NAME}:${env.BUILD_NUMBER}\'",
to: 'bcl@nclasters.org Brent.Laster@domain.com'
### LIBRARIES ### ****************************************************
#Import a library
import static <Library>
@Library('<libname>[@version]')_ [<import statement>]
#Version may be tag, branch name, etc
#Import statement for subsets
#Import statement not required
#Underscore only required if no import statement used
#Load default version of a library
@Library('myLib')
#Load specific version of library
@Library('yourLib@2.0')
#Access multiple libraries
@Library(['myLib', 'yourLib@master'])
#With import statement
@Library('myLib@1.0') import static org.demo.Utilities.*
#Add some timestamps
def commandOutput
timestamps {
commandOutput = sh(script: "${<command-to-run>}",
returnStdout: true).trim()
}
echo commandOutput
#Creating a method
// org.demo.buildUtils
package org.demo
#Defines the method
def timedGradleBuild(tasks) {
timestamps {
sh "${tool 'gradle3.2'}/bin/gradle ${tasks}"
}
}
#Invokes the pipeline above
def myUtils = new org.demo.buildUtils()
git "<gradle project to clone>"
myUtils.timedGradleBuild("clean build")
### SCRIPTED LANGUAGE SYNTAX ### ****************************************************
#Identifiers
//
def employeename
#Builtin data types (Groovy) of interest
- byte
- short (Short number)
- int (Whole numbrers)
- long (Long numbers)
- float (number with decimal points)
- char (Single character)
- Boolean (True/false)
- String
#Sample library routine
//Declares commandOutput variable
def commandOutput
timestamps {
//Sets commandOutput variable
commandOutput = sh(script: "${<command-to-run>}",
returnStdout: true).trim()
}
//Displays commandOutput variable
echo commandOutput
#Creating a method
#Stored in src/
// org.demo.buildUtils
package org.demo
//Creates the method
def timedGradleBuild(tasks) {
timestamps {
sh "${tool 'gradle3.2'}/bin/gradle ${tasks}"
}
}
#Invoking org.demo.buildUtils
//Creates an instantiation of the method
def myUtils = new org.demo.buildUtils()
git "<gradle project to clone>"
//Passes criteria into method
myUtils.timedGradleBuild("clean build")
### DECLARATIVE SYNTAX LANGUAGE ### ****************************************************
#Tools
- ant
- git
- gradle
- jdk
- jgit
- jgitapache
- maven
tools {
<tool> <tool_version>
}
#Example
tools{
gradle "gradle3.2"
}
#Options
- buildDiscarder (Only keeps so many builds)
options { buildDiscarder(logRotator(numToKeepStr: '10')) }
- disableConcurrentBuilds (Prevents concurrent builds of the same pipeline)
- retry (If pipeline fails, retry so many times)
options { retry(2) }
- skipStagesAfterUnstable (If stage in pipeline unstable, don't process
remaining stages)
options { skipStagesAfterUnstable()}
- timeout
options { timeout(time: 15, unit: 'MINUTES') }
- timestamps
options { timestamps() }
#Triggers
- cron (Pursues at interval) and pollSCM checks for updates
// Start a pipeline execution at 10 minutes past the hour
triggers { cron(10 * * * *) }
// Scan for SCM changes at 10-minute intervals
triggers { pollSCM(*/10 * * * *) }
- upstream (Takes comma-separated string) of Jenkins job and condition to check)
triggers {
upstream(upstreamProjects: 'jobA,jobB', threshold:
hudson.model.Result.SUCCESS)
}
- githubPush (Uses webhook on Github side to detect when push occurs)
triggers { githubPush() }
#parameters
- booleanParam
parameters { booleanParam(defaultValue: false,
description: 'test run?', name: 'testRun')}
- choice (Select from a list of choices)
parameters{ choice(choices: 'Windows-1\nLinux-2', description:
'Which platform?', name: 'platform')}
- file (Add a file)
parameters{ file(fileLocation: '', description: 'Select the file to
upload')}
- text (Enter some text)
parameters{ text(defaultValue: 'No message', description:
'Enter your message', name: 'userMsg')
- password (Allows to enter hidden password)
parameters{ password(defaultValue: "userpass1", description:
'User password?', name: 'userPW')}
- run (Allows used to select particular run from job)
* Filter options:
+ All Builds
+ Completed Builds
+ Successful Builds
+ Stable Builds Only
parameters{ run(name: "Last success", description:
'Last successful project', project: 'project1',
filter: 'Successful Builds')}
- string (Parameter for entering string)
parameters{ string(defaultValue: "Linux",
description: 'What platform?', name: 'platform')}
#Passing parameters into a pipeline
pipeline {
agent any
parameters{
string(defaultValue: "maintainer",
description: 'Enter user role:', name: 'userRole')
}
stages {
stage('listVals') {
steps {
//Passes parameters in
echo "User's role = ${params.userRole}"
}
}
}
}
#Condition execution options
- allOf (All statements must match)
- anyOf (Any one statement may match)
- not (Not the statement)
when {
<option> {
<criteria 1>
<criteria 2>
}
}