-
Notifications
You must be signed in to change notification settings - Fork 0
/
Jenkinsfile
584 lines (568 loc) · 28.3 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
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
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
#!/usr/bin/env groovy
def getBranch() {
env.CHANGE_BRANCH ? env.CHANGE_BRANCH : env.GIT_BRANCH
}
def getEnvironments() {
readJSON file: 'environments.json'
}
def getTestTargets(environments, testTarget) {
environments.auto_deploy_test_targets.findAll{testTarget =~ /^$it.key$/}
.collect{it -> it.value}
.flatten()
}
def getBranchTargets(environments, branchTarget) {
environments.auto_deploy_branch_targets.findAll{branchTarget =~ /^$it.key$/}
.collect{it -> it.value}
.flatten()
}
def login_to_registry() {
sh(script: '''
echo "$JFROG_CREDENTIALS_PSW" | docker login --username "$JFROG_CREDENTIALS_USR" --password-stdin "$REGISTRY_REPO"
''',
label: 'Log in to Docker Registry',
)
}
def getKubeconfigShell(clusterName) {
"""
aws eks update-kubeconfig \
--name ${clusterName} \
--kubeconfig kube-config
export KUBECONFIG=kube-config
kubectl cluster-info
"""
}
def getCloudFrontDistribution(domainName){
"""
aws cloudfront list-distributions \
--query "DistributionList.Items[?Aliases.Items!=null] | [?contains(Aliases.Items, '${domainName}')].Id" \
--output text
"""
}
def build_message(state) {
def branch = getBranch()
"Build <${BUILD_URL}|${env.BUILD_NUMBER}> ${state} for ${branch}"
}
def notify(message, channel, color, update) {
def branch = getBranch()
if (update) {
slackResponse = slackSend(channel: channel, message: message, color: color, timestamp: env.ts)
return slackResponse
} else {
slackResponse = slackSend(channel: channel, message: message, color: color)
return slackResponse
}
}
def notify_success(message) {
notify(message, env.thread, "good", false)
}
def notify_failure(message) {
notify(message, env.thread, "danger", false)
}
def notify_start(message, channel) {
notify(message, channel, "caution", false)
}
def notify_end(message, channel, color) {
notify(message, channel, color, true)
}
pipeline {
agent any
environment {
IMAGE_TAG = GIT_COMMIT.take(7)
SERVER_TAG = "${IMAGE_TAG}-Backend"
YOUR_JFROG_CREDENTIALS = credentials('YOUR_JFROG')
YOUR_JFROG_NPMRC_FILE = credentials('YOUR_JFROG_npmrc_YOUR_REPO')
}
stages {
stage('Precheck') {
stages {
stage('Get Environment Variables') {
steps {
script {
/*
* Read a JSON config file environmnts.json that has environment names as top-level keys.
* For keys for environments, use CMDB status names from:
* https://your_org.atlassian.net/wiki/spaces/PKR/pages/212798677/Tagging+and+labeling+in+Cards+environment
*
* account: The target AWS account number
* domain_name: The domain name, used to construct:
* * the cross-account role name,
* * S3 bucket name, and
* * the CloudFront distribution
*
* Thanks Stack Overflow https://stackoverflow.com/a/63683524
* for the dynamic environment variable definition tip
*/
def environments = getEnvironments()
def branch_targets = getBranchTargets(environments, getBranch())
def test_targets = getTestTargets(environments, getBranch())
env.DEPLOY = false
if (branch_targets.size() > 0) {
if( env.GIT_BRANCH.contains("PR-") ) {
env.deploy = false
}
else {
// Checking CHANGE_ID verifies we do not run deploys on an open PR
env.DEPLOY = env.CHANGE_ID ? false : true
}
}
if (test_targets.size() > 0) {
env.TEST = true
}
def sonarqube_target_env = "production"
env.IMAGE = environments.image
env.VIRTUAL_REGISTRY_REPO = environments.virtual_registry_repo
env.REGISTRY_REPO = environments.registry_url
env.REGISTRY_URL = "https://${env.REGISTRY_REPO}"
env.NAMESPACE = environments.namespace
env.SONARQUBE_ENV = environments.sonar_qube_config.target[sonarqube_target_env].environment
env.SONARQUBE_IMAGE = environments.sonar_qube_config.image
// env.SONARQUBE_PROJECT_BASE_DIR = environments.sonar_qube_config.project_base_dir
env.SONARQUBE_PROJ_KEY = environments.sonar_qube_config.project_key
env.SONARQUBE_PROJ_NAME = environments.sonar_qube_config.project_name
env.SONARQUBE_SOURCE = environments.sonar_qube_config.source
env.SONARQUBE_ENDPOINT = environments.sonar_qube_config.target[sonarqube_target_env].endpoint
env.SONARQUBE_TOKEN_NAME = environments.sonar_qube_config.target[sonarqube_target_env].token_name
def slackResponse = notify_start(build_message("STARTED"), "#credit-pricing-build-test-notifications")
env.thread = slackResponse.threadId
env.channel = slackResponse.channelId
env.ts = slackResponse.ts
}
}
}
stage ('Connect to Kubernetes') {
when { expression {env.DEPLOY} }
agent {
docker {
// Thanks https://stackoverflow.com/a/58691337 for the entrypoint trick
image "${env.REGISTRY_REPO}/${env.VIRTUAL_REGISTRY_REPO}/jshimko/kube-tools-aws:3.6.0"
args "-it --entrypoint="
registryUrl 'https://URL.YOUR_JFROG.io/'
registryCredentialsId "YOUR_JFROG"
}
}
steps {
script {
def environments = getEnvironments()
def branch_targets = getBranchTargets(environments, getBranch())
for(target in branch_targets) {
stage("Connect to ${target}"){
env.ORIGIN_DOMAIN_NAME = environments.target[target].origin_domain_name.trim()
// env.API_ORIGIN_DOMAIN_NAME = environments.target[target].api_origin_domain_name.trim()
env.ACCOUNT = environments.target[target].account.trim()
env.CLUSTER_NAME = environments.target[target].cluster_name.trim()
env.DOMAIN = environments.target[target].domain_name.trim()
env.API_DOMAIN = environments.target[target].api_domain_name.trim()
env.SNS_TOPIC = environments.target[target].sns_topic.trim()
env.SNS_TOPIC_ARN = environments.target[target].sns_topic_arn.trim()
env.SNS_TOPIC_ARN_CURRENT_POLICY = environments.target[target].sns_topic_arn_current_policy.trim()
env.SNS_TOPIC_ARN_TEST = environments.target[target].sns_topic_arn_test.trim()
env.SQS_QUEUE_IN = environments.target[target].sqs_queue_in.trim()
env.SQS_QUEUE_URL_IN = environments.target[target].sqs_queue_url_in.trim()
env.SQS_QUEUE_OUT = environments.target[target].sqs_queue_out.trim()
env.SQS_QUEUE_URL_OUT = environments.target[target].sqs_queue_url_out.trim()
env.FULL_NAME_OVERRIDE = environments.target[target].full_name_override.trim()
env.RELEASE_NAME = environments.image
withAWS(role:"${env.ORIGIN_DOMAIN_NAME}",
roleAccount:"${env.ACCOUNT}",
duration: 900,
roleSessionName: 'jenkins-session') {
// Thanks Stack Overflow https://stackoverflow.com/a/35607134 for the query
sh(script: getKubeconfigShell(env.CLUSTER_NAME),
label: 'Use kubectl to get cluster information',
)
}
}
}
}
}
}
}
}
stage('Build') {
parallel {
stage('Server Docker Build') {
steps {
dir("${env.WORKSPACE}/server") {
sh '''
printf '{"GitBranch":"%s","GitCommit":"%s","BuildNo":"%s"}' \
"$GIT_BRANCH" \
"$GIT_COMMIT" \
"$BUILD_NUMBER" \
> version.json
'''
script {
writeFile file: '.npmrc', text: env.YOUR_JFROG_NPMRC_FILE
login_to_registry()
def app = docker.build("$VIRTUAL_REGISTRY_REPO/$IMAGE:${env.SERVER_TAG}", "-f Dockerfile ..")
sh 'docker images'
docker.withRegistry(REGISTRY_URL)
{
docker.image("$VIRTUAL_REGISTRY_REPO/$IMAGE:${env.SERVER_TAG}").push()
}
}
}
}
}
stage('Web UI') {
stages {
stage('Install dependencies') {
agent {
docker {
image "${env.REGISTRY_REPO}/${env.VIRTUAL_REGISTRY_REPO}/your_org/ionic-nodejs-14:2.0"
args "-v ${WORKSPACE}:/home/alpine/project -i --entrypoint="
registryCredentialsId "YOUR_JFROG"
registryUrl env.REGISTRY_URL
}
}
steps {
dir("${env.WORKSPACE}/client") {
writeFile file: '.npmrc', text: env.YOUR_JFROG_NPMRC_FILE
sh 'npm install --unsafe-perm'
stash includes: 'node_modules/**/*', name: 'node_modules'
}
}
}
stage('Sonar Scan - Web Client') {
agent {
docker {
image "${env.VIRTUAL_REGISTRY_REPO}/${env.SONARQUBE_IMAGE}"
registryCredentialsId 'YOUR_JFROG'
registryUrl env.REGISTRY_URL
}
}
environment {
SONARQUBE_PROJ_KEY = "${environments.sonar_qube_config.project_key}:client"
SONARQUBE_PROJ_NAME = "${environments.sonar_qube_config.project_name}_client"
SONARQUBE_TOKEN = credentials("${env.SONARQUBE_TOKEN_NAME}")
SONARQUBE_PROJECT_BASE_DIR = "./client/"
}
steps {
withSonarQubeEnv("${env.SONARQUBE_ENV}") {
sh "DEBUG=false ${WORKSPACE}/bin/sonar-scanner.sh"
}
}
post {
success {
notify_success('UI Sonar Scan Success')
}
failure {
notify_failure('UI Sonar Scan Failed')
}
}
}
stage('Build - npm') {
agent {
docker {
image "${env.REGISTRY_REPO}/${env.VIRTUAL_REGISTRY_REPO}/your_org/ionic-nodejs-14:2.0"
args "-v ${WORKSPACE}:/home/alpine/project -i --entrypoint="
registryUrl 'https://URL.YOUR_JFROG.io/'
registryCredentialsId "YOUR_JFROG"
}
}
steps {
script{
def environments = getEnvironments()
def branch_targets = getBranchTargets(environments, getBranch())
for(target in branch_targets) {
dir("${env.WORKSPACE}/client") {
sh 'rm -rf node_modules'
unstash 'node_modules'
sh 'rm -rf src/Utils.js'
sh 'rm -rf src/env.json'
sh "cp ../client-envs/${target}.js src/Utils.js"
sh "cp ../client-envs/${target}.json src/env.json"
sh 'CI=false npm run build'
stash includes: 'build/**/*', name: "build-${target}"
}
}
}
}
}
stage('Test - Web') {
agent {
docker {
image "${env.REGISTRY_REPO}/${env.VIRTUAL_REGISTRY_REPO}/your_org/ionic-nodejs-14:2.0"
args "-v ${WORKSPACE}:/home/alpine/project -i --entrypoint="
registryUrl 'https://URL.YOUR_JFROG.io/'
registryCredentialsId "YOUR_JFROG"
}
}
steps {
dir("${env.WORKSPACE}/client") {
sh 'rm -rf node_modules'
unstash 'node_modules'
sh 'npm run ci-test'
}
}
post {
success {
notify_success('UI Test Success')
}
failure {
notify_failure('UI Test Failed')
}
}
}
stage('Deploy - Web') {
when { expression {env.DEPLOY} }
steps{
script{
echo 'Starting'
def environments = getEnvironments()
def branch_targets = getBranchTargets(environments, getBranch())
env.BUILD_DIR = environments.build_dir
timeout(time: 5, unit: 'MINUTES') {
lock(resource: env.DOMAIN_NAME,inversePrecedence: false) {
for(target in branch_targets) {
unstash "build-${target}"
stage("Deployment to ${target}") {
env.ACCOUNT = environments.target[target].account.trim()
env.DOMAIN_NAME = environments.target[target].domain_name.trim()
withAWS(role: env.DOMAIN_NAME,
roleAccount: env.ACCOUNT,
duration: 900,
roleSessionName: 'jenkins-session') {
env.CF_DISTRIBUTION = sh(script: getCloudFrontDistribution(env.DOMAIN_NAME),
label: 'Use AWS CLI to get Cloudfront distribution',
returnStdout: true,
).trim()
s3Upload bucket: env.DOMAIN_NAME,
file: "${env.BUILD_DIR}/"
cfInvalidate distribution: env.CF_DISTRIBUTION,
paths: ['/*']
}
}
}
}
}
echo 'Finish'
}
}
post {
success {
notify_success('UI Deploy Success')
}
failure {
notify_failure('UI Deploy Failed')
}
}
}
}
}
stage ('Run git-secrets') {
agent {
docker {
image "${env.REGISTRY_REPO}/${env.VIRTUAL_REGISTRY_REPO}/your_org/alpine-git-secrets:1.1"
args "-it -entrypoint="
registryUrl 'https://URL.YOUR_JFROG.io/'
registryCredentialsId "YOUR_JFROG"
}
}
steps {
sh '''
git secrets --install -f
git secrets --register-aws
git secrets --scan
'''
}
}
stage('Sonar Scan - Backend API') {
agent {
docker {
image "${env.VIRTUAL_REGISTRY_REPO}/${env.SONARQUBE_IMAGE}"
registryCredentialsId 'YOUR_JFROG'
registryUrl env.REGISTRY_URL
}
}
environment {
SONARQUBE_PROJ_KEY = "${environments.sonar_qube_config.project_key}:server"
SONARQUBE_PROJ_NAME = "${environments.sonar_qube_config.project_name}_server"
SONARQUBE_TOKEN = credentials("${env.SONARQUBE_TOKEN_NAME}")
SONARQUBE_PROJECT_BASE_DIR = "./server/"
}
steps {
withSonarQubeEnv("${env.SONARQUBE_ENV}") {
sh "DEBUG=false ${WORKSPACE}/bin/sonar-scanner.sh"
}
}
post {
success {
notify_success("Backend sonar scan passed")
}
failure {
notify_failure("Backend sonar scan failed")
}
}
}
}
}
stage('Backend Services Tests') {
when { not { expression {env.DEPLOY} } }
steps {
script {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
def environments = getEnvironments()
def branch_targets = getBranchTargets(environments, getBranch())
env.ACCOUNT = environments.target['sandbox'].account.trim()
env.ORIGIN_DOMAIN_NAME = environments.target['sandbox'].origin_domain_name.trim()
login_to_registry()
docker.withRegistry(REGISTRY_URL)
{
docker.image("$VIRTUAL_REGISTRY_REPO/$IMAGE:${env.SERVER_TAG}").inside("-u root -v ${WORKSPACE}:/usr/src/app/reports") {
withAWS(role:"${env.ORIGIN_DOMAIN_NAME}_tester",
roleAccount:"${env.ACCOUNT}",
duration: 900,
roleSessionName: 'jenkins-session-test') {
// Thanks https://stackoverflow.com/a/60878112
sh '''
cd /usr/src/app
npm run jest-ci
'''
}
}
}
}
}
}
post {
always {
publishHTML target: [
allowMissing : false,
alwaysLinkToLastBuild: false,
keepAll : true,
reportDir : "${WORKSPACE}/jest",
reportFiles : 'UnitTests.html',
reportName : 'Test Report'
]
}
success {
notify_success("Backend services tests passed. <${BUILD_URL}/Test_20Report|Test report>")
}
failure {
notify_failure("Backend services tests failed. <${BUILD_URL}/Test_20Report|Test report>")
}
}
}
stage ('Dependency Audit') {
steps {
script {
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
login_to_registry()
docker.withRegistry(REGISTRY_URL){
for(tag in [env.SERVER_TAG]) {
// Thanks https://stackoverflow.com/a/60878112
docker.image("$VIRTUAL_REGISTRY_REPO/$IMAGE:${tag}").inside {
sh '''
cd /usr/src/app
npm audit
'''
}
}
}
}
}
}
post {
success {
notify_success("Backend services dependency audit passed.")
}
failure {
notify_failure("Backend services dependency audit failed.")
}
}
}
stage('Deploy - Backend') {
when { expression {env.DEPLOY} }
agent {
docker {
// Thanks https://stackoverflow.com/a/58691337 for the entrypoint trick
image "${env.REGISTRY_REPO}/${env.VIRTUAL_REGISTRY_REPO}/jshimko/kube-tools-aws:3.8.1"
args "-it --entrypoint="
registryUrl 'https://URL.YOUR_JFROG.io/'
registryCredentialsId "YOUR_JFROG"
}
}
steps {
script {
def environments = getEnvironments()
def branch_targets = getBranchTargets(environments, getBranch())
for(target in branch_targets) {
stage("Deploy ${target}"){
// env.DOMAIN_NAME = environments.target[target].domain_name.trim()
// env.API_DOMAIN_NAME = environments.target[target].api_domain_name.trim()
env.SERVICE_ACCOUNT_NAME = environments.target[target].service_account_name.trim()
// env.ORIGIN_DOMAIN_NAME = environments.target[target].origin_domain_name.trim()
// env.REPLICA_COUNT = environments.target[target].replica_count.trim()
// env.API_ORIGIN_DOMAIN_NAME = environments.target[target].api_origin_domain_name.trim()
// env.CLUSTER_NAME = environments.target[target].cluster_name.trim()
// env.ACCOUNT = environments.target[target].account.trim()
withAWS(role:"${env.ORIGIN_DOMAIN_NAME}",
roleAccount:"${env.ACCOUNT}",
duration: 900,
roleSessionName: 'jenkins-session') {
// Thanks Stack Overflow https://stackoverflow.com/a/35607134 for the query
def kubeConfigShell = getKubeconfigShell(env.CLUSTER_NAME)
dir("${env.WORKSPACE}/helm") {
sh(script: """
${kubeConfigShell}
# Thanks https://github.com/helm/helm/issues/8194#issuecomment-671312246
PKG=\$(
helm package \
--app-version=${env.SERVER_TAG} \
server \
| awk '{print \$8}'
)
helm upgrade \
--install \
--atomic \
--wait \
--namespace ${env.NAMESPACE} \
--set domain=${env.DOMAIN} \
--set apiDomain=${env.API_DOMAIN} \
--set serviceAccount.name=${env.SERVICE_ACCOUNT_NAME} \
--set image.registry=${env.REGISTRY_REPO} \
--set image.tag=${env.SERVER_TAG} \
--set image.repository=${env.VIRTUAL_REGISTRY_REPO}/${env.IMAGE} \
--set snsTopic=${env.SNS_TOPIC} \
--set snsTopicArn=${env.SNS_TOPIC_ARN} \
--set snsTopicArnCurrentPolicy=${env.SNS_TOPIC_ARN_CURRENT_POLICY} \
--set snsTopicArnTest=${env.SNS_TOPIC_ARN_TEST} \
--set sqsQueueIn=${env.SQS_QUEUE_IN} \
--set sqsQueueUrlIn=${env.SQS_QUEUE_URL_IN} \
--set sqsQueueOut=${env.SQS_QUEUE_OUT} \
--set sqsQueueUrlOut=${env.SQS_QUEUE_URL_OUT} \
--set nodeEnv=${target} \
--set environment=${target} \
${env.FULL_NAME_OVERRIDE} \
"\$PKG"
helm history \
--namespace ${env.NAMESPACE} \
${env.FULL_NAME_OVERRIDE}
""",
label: 'Deploy application with helm',
)
}
}
}
}
}
}
post {
success {
notify_success("Backend deploy success")
}
failure {
notify_failure("Backend deploy failed")
}
}
}
}
post {
success {
notify_end(build_message("SUCCESS"), env.channel, "good")
}
failure {
notify_end(build_message("FAILURE"), env.channel, "danger")
}
}
}