Repository navigation
Expand file tree
/
Copy pathJenkinsfile
More file actions
603 lines (550 loc) · 34 KB
/
Copy pathJenkinsfile
File metadata and controls
603 lines (550 loc) · 34 KB
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
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
import groovy.transform.Field
// Single source for the chooseProfile choices: used by the parameters block and by refreshParameters().
@Field List<String> PROFILES = ['full', 'full-netpols', 'full-secrets', 'full-external-vault', 'operator-full-external-vault-approle', 'minimal', 'all-profiles', 'full-prefix', 'content-examples', 'operator-full', 'operator-mandants']
pipeline {
agent {
label 'high-cpu'
}
triggers {
cron(env.BRANCH_NAME == 'develop' ? '0 19 * * 5' : '')
}
options {
buildDiscarder(logRotator(numToKeepStr: '20'))
timestamps()
timeout(time: 120, unit: 'MINUTES')
}
parameters {
booleanParam(defaultValue: false, name: 'forcePushImage', description: 'Pushes the image with the current git commit as tag, even when it is on a branch')
booleanParam(defaultValue: false, name: 'noCache', description: 'Builds the docker image without cache')
choice(name: 'chooseProfile', choices: PROFILES, description: 'Starts GOP with given profile only and execute tests which belongs to profile.')
booleanParam(defaultValue: false, name: 'performRelease', description: 'Creates a GitHub Release: tags HEAD, publishes SBOM assets to the release and pushes the image to GHCR. Outside the main branch, hover over the Resolve tag stage in the stage view and click Confirm within 5 minutes, otherwise the build is aborted.')
string(defaultValue: '', name: 'releaseVersion', description: 'Version to release, schema x.y.z. Leave empty to use the suggested next patch version. Only used when performRelease is checked.')
booleanParam(defaultValue: false, name: 'skipIntegrationTests', description: 'Skips the integration tests stage')
}
environment {
BUILD_USER = sh(script: 'id -u', returnStdout: true).trim()
BUILD_GROUP = sh(script: 'getent group docker | cut -d: -f3', returnStdout: true).trim()
DOCKER_REGISTRY_BASE_URL = 'ghcr.io'
GITHUB_REPOSITORY = sh(script: "git remote get-url origin | sed -E 's#^(git@github.com:|https://github.com/)##; s#[.]git\$##'", returnStdout: true).trim()
DOCKER_IMAGE_NAME = "${env.GITHUB_REPOSITORY}"
MAVEN_IMAGE = 'maven:3-eclipse-temurin-25'
GRYPE_IMAGE = 'anchore/grype:v0.109.1'
SYFT_IMAGE = 'anchore/syft:v1.42.2'
ORAS_IMAGE = 'ghcr.io/oras-project/oras:v1.3.4'
GOLANG_IMAGE = 'golang:1.25-alpine'
SHORT_SHA = sh(script: 'git rev-parse --short=8 HEAD', returnStdout: true).trim()
BUILD_DATE = sh(script: 'date --rfc-3339 ns', returnStdout: true).trim()
K3D_CLUSTER_NAME = "k3d-gop-cluster-${env.BUILD_ID}"
FULL_IMAGE_TAG = "${env.DOCKER_REGISTRY_BASE_URL}/${env.DOCKER_IMAGE_NAME}:${env.SHORT_SHA}"
// Shared docker args for integration tests
INTEGRATION_TEST_DOCKER_ARGS = "-e KUBECONFIG=${env.WORKSPACE}/.kubeconfig.yaml -v maven-cache:/root/.m2 -v /var/run/docker.sock:/var/run/docker.sock -u :${env.BUILD_GROUP} --network=host --entrypoint ''"
}
stages {
stage('Resolve tag') {
steps {
script {
def latestTag
withCredentials([usernamePassword(
credentialsId: 'cesmarvin',
usernameVariable: 'SCM_USERNAME',
passwordVariable: 'SCM_TOKEN'
)]) {
sh "git -c credential.helper='!f() { echo username=\$SCM_USERNAME; echo password=\$SCM_TOKEN; }; f' fetch --tags"
// Ask the remote directly, so the result does not depend on the state of the local checkout.
latestTag = sh(script: "git -c credential.helper='!f() { echo username=\$SCM_USERNAME; echo password=\$SCM_TOKEN; }; f' ls-remote --tags --refs origin | sed 's#.*refs/tags/##' | grep -E '^[0-9]+\\.[0-9]+\\.[0-9]+\$' | sort -t. -k1,1n -k2,2n -k3,3n | tail -1", returnStdout: true).trim()
}
def suggestedNext = nextPatchVersion(latestTag)
refreshParameters(latestTag)
if (params.performRelease) {
env.TAG_NAME = params.releaseVersion?.trim() ?: suggestedNext
if (!(env.TAG_NAME ==~ "^\\d+\\.\\d+\\.\\d+\$")) {
error("Release version '${env.TAG_NAME}' must match schema x.y.z")
}
// Check the remote: a local tag left over from an aborted release build in a reused workspace must not block a retry.
withCredentials([usernamePassword(
credentialsId: 'cesmarvin',
usernameVariable: 'SCM_USERNAME',
passwordVariable: 'SCM_TOKEN'
)]) {
if (sh(script: "git -c credential.helper='!f() { echo username=\$SCM_USERNAME; echo password=\$SCM_TOKEN; }; f' ls-remote --tags --refs origin 'refs/tags/${env.TAG_NAME}'", returnStdout: true).trim()) {
error("Tag ${env.TAG_NAME} already exists - aborting release build.")
}
}
if (env.BRANCH_NAME != 'main') {
timeout(time: 5, unit: 'MINUTES') {
input message: "WARNING: Release ${env.TAG_NAME} would be created from branch '${env.BRANCH_NAME}', not 'main'. Continue?",
ok: 'Release from non-main branch'
}
}
// Tag locally before packaging: the Dockerfile copies .git and the version output embeds git.tags.
// The tag is pushed in 'Publish Release', after image, SBOM and OCI attachment exist.
signTag(env.TAG_NAME)
echo "Releasing version: ${env.TAG_NAME}"
} else {
// Several tags can point at HEAD, but only one may become TAG_NAME:
// - grep -E '^[0-9]+\.[0-9]+\.[0-9]+$' keeps only release versions x.y.z (e.g. 0.22.3), no other tag names
// - sort -V sorts by version number (0.10.0 is higher than 0.9.0)
// - tail -1 takes the highest one; the result is empty if there is no release tag
env.TAG_NAME = sh(returnStdout: true, script: "git --no-pager tag --points-at HEAD | grep -E '^[0-9]+\\.[0-9]+\\.[0-9]+\$' | sort -V | tail -1").trim()
echo "Resolved tag: ${env.TAG_NAME ?: 'none'}"
}
}
}
}
stage('Build') {
parallel {
stage("Test & SonarScanner") {
agent {
docker {
image "${env.MAVEN_IMAGE}"
args "-e HOME=${env.WORKSPACE}/.maven-home"
reuseNode true
}
}
steps {
withSonarQubeEnv('ces-sonar') {
sh '''
mkdir -p "$WORKSPACE/.maven-home/.m2/repository"
mvn -B \
-Dmaven.repo.local="$WORKSPACE/.maven-home/.m2/repository" \
clean verify sonar:sonar \
-Dsonar.projectKey=gitops-playground \
-Dsonar.branch.name="$BRANCH_NAME"
'''
}
}
post {
always {
junit testResults: '**/target/surefire-reports/TEST-*.xml'
}
}
}
stage("Build Image") {
steps {
script {
def buildArgs = (params.noCache ? "--no-cache " : "") +
"--build-arg BUILD_DATE='${env.BUILD_DATE}' " +
"--build-arg VCS_REF='${env.GIT_COMMIT}' "
docker.build(env.FULL_IMAGE_TAG, "${buildArgs} .")
}
}
}
}
}
stage('Security & Integration') {
parallel {
stage('SBOM & Vulnerability Scan') {
steps {
sh '''docker run --rm \
-v "$WORKSPACE:/workspace" \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
-u ":$BUILD_GROUP" \
-e NO_COLOR=1 \
"$SYFT_IMAGE" \
--output table=/workspace/sbom.txt \
--output json=/workspace/sbom.syft.json \
--output cyclonedx-json@1.6=/workspace/sbom.cdx.json \
--quiet \
"$FULL_IMAGE_TAG"
'''
sh 'sha256sum sbom.cdx.json > sbom.cdx.json.sha256'
catchError(
buildResult: 'SUCCESS',
stageResult: 'UNSTABLE',
catchInterruptions: false
) {
sh '''docker run --rm -v $WORKSPACE:/workspace \
-v /var/run/docker.sock:/var/run/docker.sock:ro \
-u :$BUILD_GROUP \
-e NO_COLOR=1 \
$GRYPE_IMAGE sbom:/workspace/sbom.syft.json \
--output table=/workspace/vulnerabilities.txt \
--output sarif=/workspace/vulnerabilities.sarif \
--sort-by severity --fail-on critical'''
}
archiveArtifacts(artifacts: 'sbom.*, vulnerabilities.*', allowEmptyArchive: false)
}
}
stage('Integration tests') {
when {
expression { return !params.skipIntegrationTests }
}
steps {
script {
def profiles = []
if (isTriggeredByTimer()
|| params.chooseProfile == 'all-profiles'
|| (env.BRANCH_NAME == 'main' && !isTriggeredByUser())) {
profiles = PROFILES - ['all-profiles', 'full-netpols', 'operator-full-external-vault']
} else if (env.BRANCH_NAME == 'develop') {
profiles = ['full-prefix', 'operator-mandants', 'operator-full']
} else {
profiles = [params.chooseProfile]
}
def dumpKubernetesDebugInfo = { profile ->
def dumpDir = "target/k8s-debug/${profile}"
docker.image("${env.GOLANG_IMAGE}").inside(env.INTEGRATION_TEST_DOCKER_ARGS) {
sh(script: """
set +e
apk add --no-cache kubectl
mkdir -p '${dumpDir}'
export KUBECONFIG='${env.WORKSPACE}/.kubeconfig.yaml'
kubectl cluster-info > '${dumpDir}/cluster-info.txt' 2>&1
kubectl get nodes -o wide > '${dumpDir}/nodes.txt' 2>&1
kubectl get namespaces -o wide > '${dumpDir}/namespaces.txt' 2>&1
kubectl get pods -A -o wide > '${dumpDir}/pods.txt' 2>&1
kubectl get events -A --sort-by=.lastTimestamp > '${dumpDir}/events.txt' 2>&1
kubectl get pvc,pv -A -o wide > '${dumpDir}/volumes.txt' 2>&1
kubectl get ingress -A -o wide > '${dumpDir}/ingress.txt' 2>&1
kubectl get networkpolicy -A -o yaml > '${dumpDir}/network-policies.yaml' 2>&1
kubectl describe all -A > '${dumpDir}/describe-all.txt' 2>&1
: > '${dumpDir}/container-logs.txt'
kubectl get pods -A --no-headers \\
-o custom-columns=NAMESPACE:.metadata.namespace,NAME:.metadata.name |
while read -r namespace pod; do
echo "===== \${namespace}/\${pod} current =====" >> '${dumpDir}/container-logs.txt'
kubectl logs -n "\${namespace}" "\${pod}" --all-containers=true --tail=200 --prefix=true >> '${dumpDir}/container-logs.txt' 2>&1
echo >> '${dumpDir}/container-logs.txt'
echo "===== \${namespace}/\${pod} previous =====" >> '${dumpDir}/container-logs.txt'
kubectl logs -n "\${namespace}" "\${pod}" --all-containers=true --previous --tail=200 --prefix=true >> '${dumpDir}/container-logs.txt' 2>&1
echo >> '${dumpDir}/container-logs.txt'
done
chown -R ${env.BUILD_USER}:${env.BUILD_GROUP} target
""", returnStatus: true)
}
archiveArtifacts artifacts: "${dumpDir}/**", allowEmptyArchive: true
}
def withK3dCluster = { profile, body ->
try {
sh "yes | KUBECONFIG=${env.WORKSPACE}/.kubeconfig.yaml ./scripts/init-cluster.sh --cluster-name=${env.K3D_CLUSTER_NAME}"
body()
} catch (Throwable t) {
dumpKubernetesDebugInfo(profile)
throw t
} finally {
sh "KUBECONFIG=${env.WORKSPACE}/.kubeconfig.yaml $HOME/.local/bin/k3d cluster delete ${env.K3D_CLUSTER_NAME}"
}
}
def createNetworkPolicyIntegrationConfig = {
def configFile = 'target/integration-test-config/network-policy.yaml'
sh 'mkdir -p target/integration-test-config'
writeFile file: configFile, text: """application:
networkPolicies:
bootstrapCidrs:
# Test-only: the GOP container uses host networking and the source address depends on the CI runner network setup.
- 0.0.0.0/0
registryAccessCidrs:
# Test-only: k3d/Docker NAT rewrites the registry source address.
- 0.0.0.0/0
"""
return configFile
}
def createExternalVaultIntegrationConfig = { vaultServer ->
def configFile = 'target/integration-test-config/external-vault.yaml'
sh 'mkdir -p target/integration-test-config'
writeFile file: configFile, text: """features:
secrets:
externalSecrets:
vault:
server: \"${vaultServer}\"
"""
return configFile
}
profiles.each { profile ->
withK3dCluster(profile) {
def externalVaultContainer = null
try {
def additionalArguments = ''
if (profile == 'full-secrets') {
docker.image("${env.GOLANG_IMAGE}").inside(env.INTEGRATION_TEST_DOCKER_ARGS) {
sh '''
apk add --no-cache kubectl
kubectl create namespace gop-job --dry-run=client -o yaml | kubectl apply -f -
kubectl apply -f ./scripts/dev/secrets/gop-secrets.yaml
'''
}
}
if (profile == 'full-external-vault' || profile == 'operator-full-external-vault' || profile == 'operator-full-external-vault-approle') {
externalVaultContainer = "external-vault-${env.BUILD_ID}"
def vaultSetupScript = profile == 'operator-full-external-vault-approle'
? 'prepare-test-vault-approle.sh'
: 'prepare-test-vault.sh'
def externalVaultServer
docker.image("${env.GOLANG_IMAGE}").inside(env.INTEGRATION_TEST_DOCKER_ARGS) {
sh 'apk add --no-cache bash kubectl docker-cli'
externalVaultServer = sh(
script: "./scripts/dev/external-vault/${vaultSetupScript} --container-name=${externalVaultContainer} --host-port=0",
returnStdout: true
).trim()
}
additionalArguments = " --config-file=${createExternalVaultIntegrationConfig(externalVaultServer)}"
}
if (profile.startsWith('operator')) {
docker.image("${env.GOLANG_IMAGE}").inside(env.INTEGRATION_TEST_DOCKER_ARGS) {
sh 'apk add --no-cache make bash curl git kubectl && make install-operator'
}
}
if (profile == 'full-netpols') {
additionalArguments = " --config-file=${createNetworkPolicyIntegrationConfig()} -x"
}
docker.image("${env.FULL_IMAGE_TAG}").inside(env.INTEGRATION_TEST_DOCKER_ARGS) {
sh "java -jar /app/gitops-playground.jar --profile=${profile}${additionalArguments}"
}
docker.image("${env.MAVEN_IMAGE}").inside(env.INTEGRATION_TEST_DOCKER_ARGS) {
try {
sh "mvn -B failsafe:integration-test failsafe:verify -Dmicronaut.environments=${profile} -Dsurefire.reportNameSuffix=${profile} -DfailIfNoTests=true"
} finally {
sh '[ ! -e target ] || chown -R $BUILD_USER:$BUILD_GROUP target'
}
}
} finally {
if (externalVaultContainer != null) {
sh "docker rm -f ${externalVaultContainer} >/dev/null 2>&1 || true"
}
}
}
}
}
}
post {
always {
junit testResults: "**/target/failsafe-reports/TEST-*.xml",
allowEmptyResults: true
}
}
}
}
}
stage('Create Draft Release') {
when {
expression { return params.performRelease }
}
steps {
script {
withCredentials([usernamePassword(
credentialsId: 'cesmarvin-ghcr',
usernameVariable: 'GH_USERNAME',
passwordVariable: 'GH_TOKEN'
)]) {
docker.image(env.GOLANG_IMAGE).inside("--entrypoint '' -u 0:0") {
// The tag is not pushed yet, so a draft is not bound to it. The tag is pushed in 'Publish Release'.
// A draft left over from an aborted release build is removed, so a retry with the same version works.
sh '''
apk add --no-cache github-cli
if [ "$(gh release view "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --json isDraft -q .isDraft 2>/dev/null)" = "true" ]; then
gh release delete "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --yes
fi
gh release create "$TAG_NAME" \
--repo "$GITHUB_REPOSITORY" \
--target "$GIT_COMMIT" \
--title "$TAG_NAME" \
--generate-notes \
--draft
'''
}
}
}
}
}
stage('Push Image') {
when {
anyOf {
branch 'main'
branch 'develop'
buildingTag()
expression { return env.TAG_NAME }
expression { return params.forcePushImage }
}
not {
triggeredBy 'TimerTrigger'
}
}
steps {
script {
def image = docker.image(env.FULL_IMAGE_TAG)
docker.withRegistry("https://${DOCKER_REGISTRY_BASE_URL}", 'cesmarvin-ghcr') {
currentBuild.description = "Image: ${env.FULL_IMAGE_TAG}"
image.push()
if (env.TAG_NAME) {
// 'latest' is pushed in 'Publish Release', once the release is complete.
image.push(env.TAG_NAME)
currentBuild.description += "\nRelease: ${env.TAG_NAME}"
}
}
}
}
}
stage('Publish Release') {
when {
expression { return params.performRelease }
}
steps {
script {
withCredentials([usernamePassword(
credentialsId: 'cesmarvin-ghcr',
usernameVariable: 'GH_USERNAME',
passwordVariable: 'GH_TOKEN'
)]) {
// Prepared on the agent, where gpg is available (see signTag). rm -f: files left by an earlier run may be owned by root.
// The key is stored with literal "\n" sequences, printf '%b' expands them
withCredentials([string(credentialsId: 'cesmarvin_signing_gpg_privkey', variable: 'GPG_KEY')]) {
sh '''
asset="gitops-playground-${TAG_NAME}.sbom.cdx.json"
rm -f "$asset" "${asset}.sha256" "${asset}.asc"
cp sbom.cdx.json "$asset"
sha256sum "$asset" > "${asset}.sha256"
export GNUPGHOME="$(mktemp -d)"
trap 'gpgconf --kill gpg-agent; rm -rf "$GNUPGHOME"' EXIT
printf '%b' "$GPG_KEY" | gpg --batch --import
gpg --batch --yes --armor --detach-sign --output "${asset}.asc" "$asset"
'''
}
docker.image(env.GOLANG_IMAGE).inside("--entrypoint '' -u 0:0") {
sh '''
apk add --no-cache github-cli
asset="gitops-playground-${TAG_NAME}.sbom.cdx.json"
# One file at a time with retries: parallel uploads to the draft failed with a transient 404.
for f in "$asset" "${asset}.sha256" "${asset}.asc"; do
for i in 1 2 3; do
gh release upload "$TAG_NAME" "$f" --repo "$GITHUB_REPOSITORY" --clobber && break
[ "$i" = 3 ] && exit 1
sleep 5
done
done
gh release view "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --json body -q .body > notes.md
download_url="https://github.com/$GITHUB_REPOSITORY/releases/download/$TAG_NAME"
{
echo
echo "## SBOM"
echo "- [$asset]($download_url/$asset)"
echo "- [${asset}.sha256]($download_url/${asset}.sha256)"
echo "- [${asset}.asc]($download_url/${asset}.asc)"
} >> notes.md
gh release edit "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --notes-file notes.md
'''
}
// Attach to the digest of the pushed image, not to the tag, so the SBOM is bound to exactly the scanned image.
// Signature and checksum describe the SBOM, so they are attached to the SBOM artifact, not to the image.
sh '''
oras() {
printf '%s' "$GH_TOKEN" | docker run --rm -i -v "$WORKSPACE:/workspace" -w /workspace "$ORAS_IMAGE" \
"$@" --username "$GH_USERNAME" --password-stdin
}
asset="gitops-playground-${TAG_NAME}.sbom.cdx.json"
IMAGE_DIGEST=$(docker inspect --format '{{range .RepoDigests}}{{println .}}{{end}}' "$FULL_IMAGE_TAG" | grep "^$DOCKER_REGISTRY_BASE_URL/$DOCKER_IMAGE_NAME@")
SBOM_REF=$(oras attach --artifact-type application/vnd.cyclonedx+json --format go-template --template '{{.reference}}' \
"$IMAGE_DIGEST" "$asset:application/vnd.cyclonedx+json")
oras attach --artifact-type application/pgp-signature "$SBOM_REF" "${asset}.asc:application/pgp-signature"
oras attach --artifact-type text/plain "$SBOM_REF" "${asset}.sha256:text/plain"
'''
// Image, SBOM assets and OCI attachment exist: push the signed tag and make the draft release public.
withCredentials([usernamePassword(
credentialsId: 'cesmarvin',
usernameVariable: 'SCM_USERNAME',
passwordVariable: 'SCM_TOKEN'
)]) {
sh """
git -c credential.helper='!f() { echo username=\$SCM_USERNAME; echo password=\$SCM_TOKEN; }; f' push origin '${env.TAG_NAME}'
"""
}
docker.image(env.GOLANG_IMAGE).inside("--entrypoint '' -u 0:0") {
sh '''
apk add --no-cache github-cli
gh release edit "$TAG_NAME" --repo "$GITHUB_REPOSITORY" --draft=false
'''
}
// Only a complete release moves 'latest'. Non-main releases got here only after confirmation in 'Resolve tag'.
docker.withRegistry("https://${DOCKER_REGISTRY_BASE_URL}", 'cesmarvin-ghcr') {
docker.image(env.FULL_IMAGE_TAG).push('latest')
}
currentBuild.description += "\nImage: ${env.DOCKER_REGISTRY_BASE_URL}/${env.DOCKER_IMAGE_NAME}:latest"
// Shows the new tag as latest on the next 'Build with Parameters' screen.
refreshParameters(env.TAG_NAME)
}
}
}
}
}
post {
unsuccessful {
script {
// The release tag is created locally before packaging. Drop it so it cannot leak into the next build in this workspace.
if (params.performRelease && env.TAG_NAME) {
sh 'git tag -d -- "$TAG_NAME" || true'
}
}
}
always {
script {
if (isTriggeredByTimer()) {
currentBuild.displayName = "#${env.BUILD_NUMBER} weekly"
emailext(
subject: "Weekly build ${currentBuild.currentResult}: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
body: '${SCRIPT, template="groovy-html.template"}',
mimeType: 'text/html',
to: env.GOP_DEVELOPERS
)
}
}
}
changed {
script {
if (!isTriggeredByTimer()) {
emailext(
subject: "${currentBuild.result}: ${env.JOB_NAME} #${env.BUILD_NUMBER}",
body: (env.ABORT_REASON ? "<p><b>${env.ABORT_REASON}</b></p>" : '') + '${SCRIPT, template="groovy-html.template"}',
mimeType: 'text/html',
recipientProviders: [
[$class: 'DevelopersRecipientProvider'],
[$class: 'RequesterRecipientProvider']
]
)
}
}
}
}
}
boolean isTriggeredByTimer() {
return !currentBuild.getBuildCauses('hudson.triggers.TimerTrigger$TimerTriggerCause').isEmpty()
}
boolean isTriggeredByUser() {
return !currentBuild.getBuildCauses('hudson.model.Cause$UserIdCause').isEmpty()
}
// Refreshes the parameter descriptions shown on the next 'Build with Parameters' screen.
void refreshParameters(String latestTag) {
properties([parameters([
booleanParam(defaultValue: false, name: 'forcePushImage', description: 'Pushes the image with the current git commit as tag, even when it is on a branch'),
booleanParam(defaultValue: false, name: 'noCache', description: 'Builds the docker image without cache'),
choice(name: 'chooseProfile', choices: PROFILES, description: 'Starts GOP with given profile only and execute tests which belongs to profile.'),
booleanParam(defaultValue: false, name: 'performRelease', description: 'Creates a GitHub Release: tags HEAD, publishes SBOM assets to the release and pushes the image to GHCR. Outside the main branch, hover over the Resolve tag stage in the stage view and click Confirm within 5 minutes, otherwise the build is aborted.'),
string(defaultValue: '', name: 'releaseVersion', description: "Version to release, schema x.y.z. Leave empty to use the next patch version after the latest remote tag (currently ${latestTag ?: 'none'}). Only used when performRelease is checked."),
booleanParam(defaultValue: false, name: 'skipIntegrationTests', description: 'Skips the integration tests stage')
])])
}
// Creates a local annotated tag signed with the GPG key of the build user. The tag is not pushed.
void signTag(String tagName) {
withEnv(["TAG_TO_SIGN=${tagName}"]) {
// The key is stored with literal "\n" sequences, printf '%b' expands them
withCredentials([string(credentialsId: 'cesmarvin_signing_gpg_privkey', variable: 'GPG_KEY')]) {
sh '''
export GNUPGHOME="$(mktemp -d)"
trap 'gpgconf --kill gpg-agent; rm -rf "$GNUPGHOME"' EXIT
printf '%b' "$GPG_KEY" | gpg --batch --import
KEY_ID=$(gpg --list-secret-keys --with-colons | awk -F: '/^sec/ {print $5; exit}')
# Tagger identity must match the key's UID, taken from the key itself
UID_STR=$(gpg --list-secret-keys --with-colons "$KEY_ID" | awk -F: '/^uid/ {print $10; exit}')
export GIT_COMMITTER_NAME="${UID_STR% <*}"
export GIT_COMMITTER_EMAIL="${UID_STR##*<}"; GIT_COMMITTER_EMAIL="${GIT_COMMITTER_EMAIL%>}"
git tag -d "$TAG_TO_SIGN" 2>/dev/null || true
git -c user.signingkey="$KEY_ID" tag -s "$TAG_TO_SIGN" -m "$TAG_TO_SIGN"
'''
}
}
}
String nextPatchVersion(String latestTag) {
if (!latestTag) {
return '0.0.1'
}
def parts = latestTag.tokenize('.').collect { it.toInteger() }
return "${parts[0]}.${parts[1]}.${parts[2] + 1}"
}