forked from julg/testJenkinsFile
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathJenkinsfile
420 lines (354 loc) · 17.5 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
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
//this is the scripted method with groovy engine
import hudson.model.Result
node {
//Configuration
def gitURL = "https://github.com/julg/testJenkinsFile.git"
def gitCredentials = ''
def warDir = "target/"
def warName = "lnevent"
def tomcatWebappsDir = "/usr/local/tomcat9-licencesNationales/webapps/"
def tomcatServiceName = "tomcat9-licencesNationales.service"
def slackChannel = "#notif-licencesnationales"
// Variables globales
def maventool
def rtMaven
def buildInfo
def server
def ENV
def serverHostnames = []
def serverCredentials = []
def executeTests
// Configuration du job Jenkins
// On garde les 5 derniers builds par branche
// On scanne les branches et les tags du Git
properties([
buildDiscarder(
logRotator(
artifactDaysToKeepStr: '',
artifactNumToKeepStr: '',
daysToKeepStr: '',
numToKeepStr: '5')
),
parameters([
gitParameter(
branch: '',
branchFilter: 'origin/(.*)',
defaultValue: 'develop',
description: 'Sélectionner la branche ou le tag à déployer',
name: 'BRANCH_TAG',
quickFilterEnabled: false,
selectedValue: 'NONE',
sortMode: 'DESCENDING_SMART',
tagFilter: '*',
type: 'PT_BRANCH_TAG'),
choice(choices: ['DEV', 'TEST', 'PROD'], description: 'Sélectionner l\'environnement cible', name: 'ENV'),
booleanParam(defaultValue: false, description: 'Voulez-vous exécuter les tests ?', name: 'executeTests')
])
])
stage('Set environnement variables') {
try {
env.JAVA_HOME = "${tool 'Open JDK 11'}"
env.PATH = "${env.JAVA_HOME}/bin:${env.PATH}"
maventool = tool 'Maven 3.3.9'
rtMaven = Artifactory.newMavenBuild()
server = Artifactory.server '-1137809952@1458918089773'
rtMaven.tool = 'Maven 3.3.9'
rtMaven.opts = '-Xms1024m -Xmx4096m'
if (params.BRANCH_TAG == null) {
throw new Exception("Variable BRANCH_TAG is null")
} else {
echo "Branch to deploy = ${params.BRANCH_TAG}"
}
if (params.ENV == null) {
throw new Exception("Variable ENV is null")
} else {
ENV = params.ENV
echo "Target environnement = ${ENV}"
}
if (ENV == 'DEV') {
serverHostnames.add('hostname.server1-dev')
serverCredentials.add('cirse1-dev-ssh-key')
serverHostnames.add('hostname.server2-dev')
serverCredentials.add('cirse2-dev-ssh-key')
} else if (ENV == 'TEST') {
serverHostnames.add('hostname.server1-test')
serverCredentials.add('cirse1-test-ssh-key')
serverHostnames.add('hostname.server2-test')
serverCredentials.add('cirse2-test-ssh-key')
} else if (ENV == 'PROD') {
serverHostnames.add('hostname.server1-prod')
serverCredentials.add('cirse1-prod-ssh-key')
serverHostnames.add('hostname.server2-prod')
serverCredentials.add('cirse2-prod-ssh-key')
}
if (params.executeTests == null) {
executeTests = false
} else {
executeTests = params.executeTests
}
echo "executeTests = ${executeTests}"
} catch (e) {
currentBuild.result = hudson.model.Result.NOT_BUILT.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
throw e
}
}
stage('SCM checkout') {
try {
checkout([
$class : 'GitSCM',
branches : [[name: "${params.BRANCH_TAG}"]],
doGenerateSubmoduleConfigurations: false,
extensions : [],
submoduleCfg : [],
userRemoteConfigs : [[credentialsId: "${gitCredentials}", url: "${gitURL}"]]
])
} catch (e) {
currentBuild.result = hudson.model.Result.FAILURE.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
throw e
}
}
if ("${executeTests}" == 'true') {
stage('test') {
try {
rtMaven.run pom: 'pom.xml', goals: 'clean test'
junit allowEmptyResults: true, testResults: '/target/surefire-reports/*.xml'
} catch (e) {
currentBuild.result = hudson.model.Result.UNSTABLE.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
// Si les tests ne passent pas, on mets le build en UNSTABLE et on continue
//throw e
}
}
} else {
echo "Tests are skipped"
}
// stage('edit-properties') {
// try {
// if (ENV == 'DEV') {
// withCredentials([
// usernamePassword(credentialsId: 'tomcatuser', passwordVariable: 'pass', usernameVariable: 'username'),
// string(credentialsId: 'periscope.oracle', variable: 'url')
// ]) {
// echo 'Edition application-dev.properties'
// echo "--------------------------"
// original = readFile "web/src/main/resources/application-dev.properties"
// newconfig = original
// newconfig = newconfig.replaceAll("spring.main.allow-bean-definition-overriding=true", "")
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.url=${url}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.username=${username}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.password=${pass}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.driver-class-name=oracle.jdbc.OracleDrive"
// writeFile file: "web/src/main/resources/application-dev.properties", text: "${newconfig}"
// }
// }
// if (ENV == 'TEST') {
// withCredentials([
// usernamePassword(credentialsId: 'tomcatuser', passwordVariable: 'pass', usernameVariable: 'username'),
// string(credentialsId: 'periscope.oracle', variable: 'url')
// ]) {
// echo 'Edition application-test.properties'
// echo "--------------------------"
// original = readFile "web/src/main/resources/application-test.properties"
// newconfig = original
// newconfig = newconfig.replaceAll("spring.main.allow-bean-definition-overriding=true", "")
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.url=${url}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.username=${username}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.password=${pass}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.driver-class-name=oracle.jdbc.OracleDrive"
// writeFile file: "web/src/main/resources/application-test.properties", text: "${newconfig}"
// }
// }
// if (ENV == 'PROD') {
// withCredentials([
// usernamePassword(credentialsId: 'tomcatuser', passwordVariable: 'pass', usernameVariable: 'username'),
// string(credentialsId: 'periscope.oracle', variable: 'url')
// ]) {
// echo 'Edition application-prod.properties'
// echo "--------------------------"
// original = readFile "web/src/main/resources/application-prod.properties"
// newconfig = original
// newconfig = newconfig.replaceAll("spring.main.allow-bean-definition-overriding=true", "")
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.url=${url}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.username=${username}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.password=${pass}"
// newconfig = newconfig + System.getProperty("line.separator") + "sujets.datasource.driver-class-name=oracle.jdbc.OracleDrive"
// writeFile file: "web/src/main/resources/application-prod.properties", text: "${newconfig}"
// }
// }
// } catch(e) {
// currentBuild.result = hudson.model.Result.FAILURE.toString()
// notifySlack(slackChannel,e.getLocalizedMessage())
// throw e
// }
// }
stage('compile-package') {
try {
if (ENV == 'DEV') {
echo 'Compile for dev profile'
echo "--------------------------"
sh "'${maventool}/bin/mvn' -Dmaven.test.skip=true clean package -DfinalName='${warName}' -DbaseDir='${tomcatWebappsDir}${warName}' -Pdev"
}
if (ENV == 'TEST') {
echo 'Compile for test profile'
echo "--------------------------"
sh "'${maventool}/bin/mvn' -Dmaven.test.skip=true clean package -DfinalName='${warName}' -DbaseDir='${tomcatWebappsDir}${warName}' -Ptest"
}
if (ENV == 'PROD') {
echo 'Compile for prod profile'
echo "--------------------------"
sh "'${maventool}/bin/mvn' -Dmaven.test.skip=true clean package -DfinalName='${warName}' -DbaseDir='${tomcatWebappsDir}${warName}' -Pprod"
}
} catch(e) {
currentBuild.result = hudson.model.Result.FAILURE.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
throw e
}
}
//stage('sonarqube analysis'){
// withSonarQubeEnv('SonarQube Server2'){ cf : jenkins/configuration/sonarQube servers ==> between the quotes put the name we gave to the server
// sh "${maventool}/bin/mvn sonar:sonar"
// }
// }
stage('artifact') {
try {
archive "${warDir}${warName}.war"
} catch(e) {
currentBuild.result = hudson.model.Result.FAILURE.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
throw e
}
}
stage ('stop tomcat'){
for (int i = 0; i < serverHostnames.size(); i++) { //Pour chaque serveur
try {
sshagent(credentials: ["${serverCredentials[i]}"]) {
withCredentials([
usernamePassword(credentialsId: 'tomcatuser', passwordVariable: 'pass', usernameVariable: 'username'),
string(credentialsId: "${serverHostnames[i]}", variable: 'hostname'),
string(credentialsId: 'service.status', variable: 'status'),
string(credentialsId: 'service.stop', variable: 'stop'),
string(credentialsId: 'service.start', variable: 'start')
]) {
echo "Stop service on ${serverHostnames[i]}"
echo "--------------------------"
try {
echo 'get service status'
sh "ssh -tt ${username}@${hostname} \"${status} ${tomcatServiceName}\""
echo 'stop the service'
sh "ssh -tt ${username}@${hostname} \"${stop} ${tomcatServiceName}\""
} catch(e) {
// Maybe the tomcat is not running
echo 'maybe the service is not running'
echo 'we try to start the service'
sh "ssh -tt ${username}@${hostname} \"${start} ${tomcatServiceName}\""
echo 'get service status'
sh "ssh -tt ${username}@${hostname} \"${status} ${tomcatServiceName}\""
echo 'stop the service'
sh "ssh -tt ${username}@${hostname} \"${stop} ${tomcatServiceName}\""
}
}
}
} catch(e) {
currentBuild.result = hudson.model.Result.FAILURE.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
throw e
}
}
}
stage ('deploy to tomcat'){
for (int i = 0; i < serverHostnames.size(); i++) { //Pour chaque serveur
try {
sshagent(credentials: ["${serverCredentials[i]}"]) {
withCredentials([
usernamePassword(credentialsId: 'tomcatuser', passwordVariable: 'pass', usernameVariable: 'username'),
string(credentialsId: "${serverHostnames[i]}", variable: 'hostname')
]) {
echo "Deploy to ${serverHostnames[i]}"
echo "--------------------------"
sh "ssh -tt ${username}@${hostname} \"rm -r ${tomcatWebappsDir}${warName} ${tomcatWebappsDir}${warName}.war\""
sh "scp ${warDir}${warName}.war ${username}@${hostname}:${tomcatWebappsDir}"
}
}
} catch(e) {
currentBuild.result = hudson.model.Result.FAILURE.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
throw e
}
}
}
stage ('restart tomcat'){
for (int i = 0; i < serverHostnames.size(); i++) { //Pour chaque serveur
try {
sshagent(credentials: ["${serverCredentials[i]}"]) {
withCredentials([
usernamePassword(credentialsId: 'tomcatuser', passwordVariable: 'pass', usernameVariable: 'username'),
string(credentialsId: "${serverHostnames[i]}", variable: 'hostname'),
string(credentialsId: 'service.status', variable: 'status'),
string(credentialsId: 'service.start', variable: 'start')
]) {
echo "Restart service on ${serverHostnames[i]}"
echo "--------------------------"
echo 'start service'
sh "ssh -tt ${username}@${hostname} \"${start} ${tomcatServiceName}\""
echo 'get service status'
sh "ssh -tt ${username}@${hostname} \"${status} ${tomcatServiceName}\""
}
}
} catch(e) {
currentBuild.result = hudson.model.Result.FAILURE.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
throw e
}
}
}
stage ('Artifactory configuration') {
try {
rtMaven.deployer server: server, releaseRepo: 'libs-release-local', snapshotRepo: 'libs-snapshot-local'
buildInfo = Artifactory.newBuildInfo()
buildInfo = rtMaven.run pom: 'pom.xml', goals: '-U clean install -Dmaven.test.skip=true '
rtMaven.deployer.deployArtifacts buildInfo
buildInfo = rtMaven.run pom: 'pom.xml', goals: 'clean install -Dmaven.repo.local=.m2 -Dmaven.test.skip=true'
buildInfo.env.capture = true
server.publishBuildInfo buildInfo
} catch(e) {
currentBuild.result = hudson.model.Result.FAILURE.toString()
notifySlack(slackChannel,e.getLocalizedMessage())
throw e
}
}
currentBuild.result = hudson.model.Result.SUCCESS.toString()
notifySlack(slackChannel,"Congratulation !")
}
def notifySlack(String slackChannel, String info = '') {
def colorCode = '#848484' // Gray
switch (currentBuild.result) {
case 'NOT_BUILT':
colorCode = '#FFA500' // Orange
break
case 'SUCCESS':
colorCode = '#00FF00' // Green
break
case 'UNSTABLE':
colorCode = '#FFFF00' // Yellow
break
case 'FAILURE':
colorCode = '#FF0000' // Red
break;
}
String message = """
*Jenkins Build*
Job name: `${env.JOB_NAME}`
Build number: `#${env.BUILD_NUMBER}`
Build status: `${currentBuild.result}`
Branch or tag: `${params.BRANCH_TAG}`
Target environment: `${params.ENV}`
Message: `${info}`
Build details: <${env.BUILD_URL}/console|See in web console>
""".stripIndent()
return slackSend(tokenCredentialId: "slack_token",
channel: "${slackChannel}",
color: colorCode,
message: message)
}