-
Notifications
You must be signed in to change notification settings - Fork 571
/
Jenkinsfile-Release
272 lines (238 loc) · 12.3 KB
/
Jenkinsfile-Release
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
/*
* Copyright (c) 2016-present Sonatype, Inc. All rights reserved.
* Includes the third-party code listed at http://links.sonatype.com/products/nexus/attributions.
* "Sonatype" is a trademark of Sonatype, Inc.
*/
@Library(['private-pipeline-library', 'jenkins-shared']) _
import com.sonatype.jenkins.pipeline.GitHub
import com.sonatype.jenkins.pipeline.OsTools
import com.sonatype.jenkins.shared.Expectation
String OPENJDK17 = 'OpenJDK 17'
List<String> javaVersions = [OPENJDK17]
properties([
parameters([
string(defaultValue: '', description: 'New Nexus Repository Manager Version', name: 'nexus_repository_manager_version'),
string(defaultValue: '', description: 'New Nexus Repository Manager Version Sha256', name: 'nexus_repository_manager_version_sha'),
booleanParam(defaultValue: false, description: 'Skip Pushing of Docker Image and Tags', name: 'skip_push'),
booleanParam(defaultValue: false, description: 'Only update the latest tag', name: 'update_latest_only')
])
])
node('ubuntu-zion') {
def commitId, commitDate, version, imageId, alpineImageId, branch
def organization = 'sonatype',
gitHubRepository = 'docker-nexus3',
credentialsId = 'jenkins-github',
imageName = 'sonatype/nexus3',
archiveName = 'docker-nexus3',
dockerHubRepository = 'nexus3'
GitHub gitHub
def JAVA_17 = 'java17'
dockerFileLocations = [
"${pwd()}/Dockerfile.java17",
"${pwd()}/Dockerfile.rh.ubi.java17",
"${pwd()}/Dockerfile.alpine.java17"
]
try {
stage('Preparation') {
deleteDir()
OsTools.runSafe(this, "docker system prune -a -f")
def checkoutDetails = checkout scm
branch = checkoutDetails.GIT_BRANCH == 'origin/main' ? 'main' : checkoutDetails.GIT_BRANCH
commitId = checkoutDetails.GIT_COMMIT
commitDate = OsTools.runSafe(this, "git show -s --format=%cd --date=format:%Y%m%d-%H%M%S ${commitId}")
OsTools.runSafe(this, 'git config --global user.email [email protected]')
OsTools.runSafe(this, 'git config --global user.name Sonatype CI')
version = readVersion()
def apiToken
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId: credentialsId,
usernameVariable: 'GITHUB_API_USERNAME',
passwordVariable: 'GITHUB_API_PASSWORD']]) {
apiToken = env.GITHUB_API_PASSWORD
}
gitHub = new GitHub(this, "${organization}/${gitHubRepository}", apiToken)
if (params.nexus_repository_manager_version && params.nexus_repository_manager_version_sha) {
stage('Update Repository Manager Version') {
OsTools.runSafe(this, "git checkout ${branch}")
dockerFileLocations.each { updateRepositoryManagerVersion(it) }
version = getShortVersion(params.nexus_repository_manager_version)
}
}
}
stage('Build Images') {
gitHub.statusUpdate commitId, 'pending', 'build', 'Build is running'
def dockerfilePath = 'Dockerfile.java17'
def baseImage = extractBaseImage(dockerfilePath)
def baseImageRefFactory = load 'scripts/BaseImageReference.groovy'
def baseImageReference = baseImageRefFactory.build(this, baseImage as String)
def baseImageReferenceStr = baseImageReference.getReference()
def hash = OsTools.runSafe(this, "docker build --quiet --label base-image-ref='${baseImageReferenceStr}' --no-cache --tag ${imageName} . -f ${dockerfilePath}")
imageId = hash.split(':')[1]
// Build Alpine Image
def alpineDockerfilePath = 'Dockerfile.alpine.java17'
def alpineHash = OsTools.runSafe(this, "docker build --quiet --no-cache --tag ${imageName}-alpine . -f ${alpineDockerfilePath}")
alpineImageId = alpineHash.split(':')[1]
if (currentBuild.result == 'FAILURE') {
gitHub.statusUpdate commitId, 'failure', 'build', 'Build failed'
return
} else {
gitHub.statusUpdate commitId, 'success', 'build', 'Build succeeded'
}
}
stage('Evaluate Policies') {
def imagesToScan = [
[name: 'docker-nexus3', image: imageName],
[name: 'docker-nexus3-alpine', image: "${imageName}-alpine"]
]
imagesToScan.each { imageConfig ->
runEvaluation({ stage ->
def iqApplicationName = imageConfig.name
def imageToScan = imageConfig.image
nexusPolicyEvaluation(
iqStage: stage,
iqApplication: iqApplicationName,
iqScanPatterns: [[scanPattern: "container:${imageToScan}"]],
failBuildOnNetworkError: true,
)
}, 'release')
}
}
if (currentBuild.result == 'FAILURE') {
return
}
if (params.nexus_repository_manager_version && params.nexus_repository_manager_version_sha) {
stage('Commit Automated Code Update') {
withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'jenkins-github',
usernameVariable: 'GITHUB_API_USERNAME', passwordVariable: 'GITHUB_API_PASSWORD']]) {
def commitMessage = "Update Repository Manager to ${params.nexus_repository_manager_version}."
if (!params.update_latest_only) {
OsTools.runSafe(this, """
git add .
git commit -m '${commitMessage}'
git push https://${env.GITHUB_API_USERNAME}:${env.GITHUB_API_PASSWORD}@github.com/${organization}/${gitHubRepository}.git ${branch}
""")
}
}
}
}
stage('Archive') {
dir('build/target') {
OsTools.runSafe(this, "docker save ${imageName} | gzip > ${archiveName}.tar.gz")
archiveArtifacts artifacts: "${archiveName}.tar.gz", onlyIfSuccessful: true
}
}
if (branch == 'main' && !params.skip_push && !params.update_latest_only) {
stage('Push image') {
def dockerhubApiToken
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId: 'docker-hub-credentials',
usernameVariable: 'DOCKERHUB_API_USERNAME',
passwordVariable: 'DOCKERHUB_API_PASSWORD']]) {
// Push UBI image
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:${version}")
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:${version}-ubi")
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:${version}-java17-ubi")
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:latest")
// Push Alpine Image
OsTools.runSafe(this, "docker tag ${alpineImageId} ${organization}/${dockerHubRepository}:${version}-alpine")
OsTools.runSafe(this, "docker tag ${alpineImageId} ${organization}/${dockerHubRepository}:${version}-java17-alpine")
OsTools.runSafe(this, """
docker login --username ${env.DOCKERHUB_API_USERNAME} --password ${env.DOCKERHUB_API_PASSWORD}
""")
OsTools.runSafe(this, "docker push --all-tags ${organization}/${dockerHubRepository}")
response = OsTools.runSafe(this, """
curl -X POST https://hub.docker.com/v2/users/login/ \
-H 'cache-control: no-cache' -H 'content-type: application/json' \
-d '{ "username": "${env.DOCKERHUB_API_USERNAME}", "password": "${env.DOCKERHUB_API_PASSWORD}" }'
""")
token = readJSON text: response
dockerhubApiToken = token.token
def readme = readFile file: 'README.md', encoding: 'UTF-8'
readme = readme.replaceAll("(?s)<!--.*?-->", "")
readme = readme.replace("\"", "\\\"")
readme = readme.replace("\n", "\\n")
response = httpRequest customHeaders: [[name: 'authorization', value: "JWT ${dockerhubApiToken}"]],
acceptType: 'APPLICATION_JSON', contentType: 'APPLICATION_JSON', httpMode: 'PATCH',
requestBody: "{ \"full_description\": \"${readme}\" }",
url: "https://hub.docker.com/v2/repositories/${organization}/${dockerHubRepository}/"
// push to internal repos
withSonatypeDockerRegistry() {
sh "docker tag ${imageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}"
sh "docker tag ${imageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-ubi"
sh "docker tag ${imageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-java17-ubi"
sh "docker tag ${alpineImageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-alpine"
sh "docker tag ${alpineImageId} docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-java17-alpine"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-ubi"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-java17-ubi"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-alpine"
sh "docker push docker-all.repo.sonatype.com/sonatype-internal/${dockerHubRepository}:${version}-java17-alpine"
}
}
}
stage('Push tags') {
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId: credentialsId,
usernameVariable: 'GITHUB_API_USERNAME',
passwordVariable: 'GITHUB_API_PASSWORD']]) {
OsTools.runSafe(this, "git tag ${version}")
OsTools.runSafe(this, """
git push \
https://${env.GITHUB_API_USERNAME}:${env.GITHUB_API_PASSWORD}@github.com/${organization}/${gitHubRepository}.git \
${version}
""")
}
OsTools.runSafe(this, "git tag -d ${version}")
}
}
else if(params.update_latest_only) {
stage('Push tags') {
withCredentials([[$class: 'UsernamePasswordMultiBinding',
credentialsId: 'docker-hub-credentials',
usernameVariable: 'DOCKERHUB_API_USERNAME',
passwordVariable: 'DOCKERHUB_API_PASSWORD']]) {
OsTools.runSafe(this, "docker tag ${imageId} ${organization}/${dockerHubRepository}:latest")
OsTools.runSafe(this, """
docker login --username ${env.DOCKERHUB_API_USERNAME} --password ${env.DOCKERHUB_API_PASSWORD}
""")
OsTools.runSafe(this, "docker push --all-tags ${organization}/${dockerHubRepository}")
}
}
}
} finally {
OsTools.runSafe(this, "docker logout")
OsTools.runSafe(this, "docker system prune -a -f")
OsTools.runSafe(this, 'git clean -f && git reset --hard origin/main')
}
}
def readVersion() {
def content = readFile 'Dockerfile.java17'
for (line in content.split('\n')) {
if (line.startsWith('ARG NEXUS_VERSION=')) {
return getShortVersion(line.substring(18))
}
}
error 'Could not determine version.'
}
def getShortVersion(version) {
return version.split('-')[0]
}
def updateRepositoryManagerVersion(dockerFileLocation) {
def dockerFile = readFile(file: dockerFileLocation)
def metaVersionRegex = /(version=")(\d\.\d{1,3}\.\d\-\d{2})(" \\)/
def metaShortVersionRegex = /(release=")(\d\.\d{1,3}\.\d)(" \\)/
def versionRegex = /(ARG NEXUS_VERSION=)(\d\.\d{1,3}\.\d\-\d{2})/
def shaRegex = /(ARG NEXUS_DOWNLOAD_SHA256_HASH=)([A-Fa-f0-9]{64})/
dockerFile = dockerFile.replaceAll(metaVersionRegex, "\$1${params.nexus_repository_manager_version}\$3")
dockerFile = dockerFile.replaceAll(metaShortVersionRegex,
"\$1${params.nexus_repository_manager_version.substring(0, params.nexus_repository_manager_version.indexOf('-'))}\$3")
dockerFile = dockerFile.replaceAll(versionRegex, "\$1${params.nexus_repository_manager_version}")
dockerFile = dockerFile.replaceAll(shaRegex, "\$1${params.nexus_repository_manager_version_sha}")
writeFile(file: dockerFileLocation, text: dockerFile)
}
def extractBaseImage (dockerFileLocation) {
def dockerFile = readFile(file: dockerFileLocation)
def baseImageRegex = "FROM\\s+([^\\s]+)"
def usedImages = dockerFile =~ baseImageRegex
return usedImages[0][1]
}