-
Notifications
You must be signed in to change notification settings - Fork 18
/
Jenkinsfile-promote
285 lines (264 loc) · 13.1 KB
/
Jenkinsfile-promote
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
@Library("titan-library") _
def getTagList(String repoUrl) {
def TAG_LIST = []
def TAG_LIST_STRING = sh (
script: "git ls-remote --refs --tags ${repoUrl} | awk -Ftags/ '{print \$2}'",
returnStdout: true
).trim()
TAG_LIST_STRING.split('\\n').each {
TAG_LIST << it
}
return TAG_LIST
}
pipeline {
agent any
tools {
jdk "java-21"
maven 'default'
git 'git'
}
environment {
TRUNK_BRANCH_NAME = 'main'
REPO_NAME = "${GIT_URL.split('/')[4].split('\\.')[0]}"
BRANCH_NAME = "${GIT_BRANCH.startsWith('origin/') ? GIT_BRANCH['origin/'.length()..-1] : GIT_BRANCH}"
GITLAB_OWNER = "${GIT_URL.split('/')[3]}"
GITLAB_REPO = "https://gitlab.tinkarbuild.com/${GITLAB_OWNER}/${REPO_NAME}.git"
GITLAB_RELEASE_API = "https://gitlab.tinkarbuild.com/api/v4/projects/${GITLAB_OWNER}%2F${REPO_NAME}/releases"
GITLAB_CREDS_ID = 'vault-gitlab-user-pat'
GITHUB_OWNER = "ikmdev"
GITHUB_REPO = "https://github.com/${GITHUB_OWNER}/${REPO_NAME}.git"
GITHUB_RELEASE_API = "https://api.github.com/repos/${GITHUB_OWNER}/${REPO_NAME}/releases"
GITHUB_UPLOAD_API = "https://uploads.github.com/repos/${GITHUB_OWNER}/${REPO_NAME}/releases"
GITHUB_CREDS_ID = 'github-promote-pat'
}
options {
skipDefaultCheckout(false)
timestamps()
ansiColor('xterm')
}
stages {
stage('Initialize') {
steps{
//Clean before checkout / build
cleanWs()
checkout scm
sh "printenv"
script {
//Get POM info
pomModel = readMavenPom(file: 'pom.xml')
pomVersion = pomModel.getVersion()
isSnapshot = pomVersion.contains("-SNAPSHOT")
promoteTag = env.TAG_NAME
promoteCommit = env.GIT_COMMIT
//Prevent Promotion of non-Semantic Versions and Tags
if(!semanticVersion.isSemanticVersion(pomVersion) || !semanticVersion.isSemanticVersion(promoteTag)) {
echo "ERROR: Current version ${pomVersion} does not adhere to semantic versioning."
fail()
}
//Prevent build from running for SNAPSHOT versions
if(isSnapshot) {
echo "ERROR: Current version ${pomVersion} is already a release version."
fail()
}
//Prevent build from running if there is no release tag
if (promoteTag == '') {
echo "ERROR: Code Promotion requires a tagged release. The command 'git tag --contains' returns: '${promoteTag}'"
fail()
}
//Only push code & tag if it is not already on GitHub
withCredentials([gitUsernamePassword(credentialsId: GITHUB_CREDS_ID, gitToolName: 'git')]) {
GITHUB_TAG_LIST = getTagList(GITHUB_REPO)
}
boolGitHubTagExists = GITHUB_TAG_LIST.contains(promoteTag)
echo """
promoteTag: ${promoteTag} \
GITHUB_TAG_LIST: ${GITHUB_TAG_LIST} \
boolGitHubTagExists: ${boolGitHubTagExists}
"""
}
}
}
stage('Check tag is associated with GitLab Release') {
steps{
script {
echo 'Starting GitLab REST request'
//Get release data from GitLab REST API
withCredentials([usernamePassword(credentialsId: GITLAB_CREDS_ID, passwordVariable: 'pw', usernameVariable: 'user')]) {
echo "Username: ${user}"
GITLAB_RELEASE_RESPONSE = sh(
script: """
curl -L \
-X GET \
""" + ' -H "PRIVATE-TOKEN: $pw" ' + """ \
${GITLAB_RELEASE_API}/${promoteTag} \
""",
returnStdout: true
).trim()
echo 'Request finished'
}
echo "GitLab GET Release Response (expect release data json): ${GITLAB_RELEASE_RESPONSE}"
GITLAB_RELEASE_JSON = readJSON text: GITLAB_RELEASE_RESPONSE
//Prevent non-release tags from being promoted
if (GITLAB_RELEASE_JSON['message'] && GITLAB_RELEASE_JSON['message'].contains('Not Found')) {
echo "ERROR: GitLab Response: ${GITLAB_RELEASE_JSON}"
echo "ERROR: Code Promotion requires a tagged release. The tag '${promoteTag}' is not associated with a GitLab Release."
fail()
}
}
}
}
stage('Check tag is NOT already a GitHub Release') {
steps{
script {
//Get release data from GitLab REST API
withCredentials([usernamePassword(credentialsId: GITHUB_CREDS_ID, passwordVariable: 'pw', usernameVariable: 'user')]) {
GITHUB_RELEASE_RESPONSE = sh (
script: """
set -x
curl -L \
-X GET \
-H "Accept: application/vnd.github+json" \
""" + ' -H "Authorization: Bearer $pw" ' + """ \
-H "X-GitHub-Api-Version: 2022-11-28" \
${GITHUB_RELEASE_API}/tags/${promoteTag} \
""",
returnStdout: true
).trim()
}
echo "GitHub GET Release Response (expect '404 not found'): ${GITHUB_RELEASE_RESPONSE}"
GITHUB_RELEASE_JSON = readJSON text: GITHUB_RELEASE_RESPONSE
//Prevent duplicate releases of a tag
if (!GITHUB_RELEASE_JSON['message'].contains('Not Found')) {
echo "ERROR: GitHub Response: ${GITHUB_RELEASE_JSON}"
echo "ERROR: Code Promotion can only be performed once for each tag. The tag '${promoteTag}' is already associated with a GitHub Release."
fail()
}
}
}
}
stage('Push Commit to GitHub') {
tools {
git "git"
}
steps {
script {
withCredentials([gitUsernamePassword(credentialsId: GITHUB_CREDS_ID, gitToolName: 'git')]) {
//Is this commit on GitHub?
echo "Adding GitHub remote..."
sh """
git remote rm downstream || true
git remote add downstream ${GITHUB_REPO} || true
git remote -v
git fetch downstream
"""
boolCommitExistsOnGitHub = sh (
script: "git branch --contains ${promoteCommit} --remotes --list \'downstream/${TRUNK_BRANCH_NAME}\'",
returnStdout: true
).trim() as Boolean
echo "Commit Exists on GitHub = ${boolCommitExistsOnGitHub}"
//Push code to GitHub if commit is not already there
if (!boolCommitExistsOnGitHub) {
echo "Pushing Code to GitHub"
sh "git push downstream HEAD:${TRUNK_BRANCH_NAME}"
}
}
}
}
}
stage('Push Tag to GitHub') {
when {
expression {
!boolGitHubTagExists //Only push tag if it is not already on GitHub
}
}
tools {
git "git"
}
steps {
script {
withCredentials([gitUsernamePassword(credentialsId: GITHUB_CREDS_ID, gitToolName: 'git')]) {
//Push tag to GitHub
echo "Pushing Tag ${promoteTag}..."
sh "git push downstream refs/tags/${promoteTag}"
//Get updated tag list after pushing tag
UPDATED_GITHUB_TAG_LIST = getTagList(GITHUB_REPO)
}
//Confirm tag was pushed to GitHub
boolGitHubTagExists = UPDATED_GITHUB_TAG_LIST.contains(promoteTag)
if(boolGitHubTagExists == false) {
echo "ERROR: Push to GitHub did not complete..."
echo """
promoteTag: ${promoteTag} \
UPDATED GITHUB_TAG_LIST: ${GITHUB_TAG_LIST} \
UPDATED boolGitHubTagExists: ${boolGitHubTagExists}
"""
fail()
}
}
}
}
stage('Create GitHub Release') {
steps {
script {
withCredentials([usernamePassword(credentialsId: GITHUB_CREDS_ID, passwordVariable: 'pw', usernameVariable: 'user')]) {
GITHUB_CREATE_RELEASE_RESPONSE = sh(
script: """
set -x
curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
""" + ' -H "Authorization: Bearer $pw" ' + """ \
-H "X-GitHub-Api-Version: 2022-11-28" \
${GITHUB_RELEASE_API} \
-d '{
"tag_name":"${promoteTag}",
"target_commitish":"main",
"name":"${GITLAB_RELEASE_JSON['name']}",
"draft":false,
"prerelease":false,
"generate_release_notes":false,
"body":"${GITLAB_RELEASE_JSON['description'].replaceAll("\n","\\\\n")}"
}'
""",
returnStdout: true
).trim()
}
echo "GitHub CREATE Release Response: ${GITHUB_CREATE_RELEASE_RESPONSE}"
GITHUB_CREATE_RELEASE_JSON = readJSON text: GITHUB_CREATE_RELEASE_RESPONSE
}
}
}
stage('Promote Release Assets from Nexus to GitHub') {
steps {
script {
//Get artifact links from GitLab release data
RELEASE_ARTIFACTS_JSON = GITLAB_RELEASE_JSON['assets']['links']
//Get Release ID from GitHub release data
GITHUB_RELEASE_ID = GITHUB_CREATE_RELEASE_JSON['id']
//Download GitLab Release Assets to stdin and upload directly to GitHub
withCredentials([usernamePassword(credentialsId: GITHUB_CREDS_ID, passwordVariable: 'pw', usernameVariable: 'user')]) {
RELEASE_ARTIFACTS_JSON.each {
asset_name = it['url'].split('/')[-1]
asset_label = it['name'].replaceAll(' ','%20')
GITHUB_UPLOAD_RELEASE_ASSET_RESPONSE = sh(
script: """
set -x
curl ${it['url']} | curl -L \
-X POST \
-H "Accept: application/vnd.github+json" \
""" + ' -H "Authorization: Bearer $pw" ' + """ \
-H "X-GitHub-Api-Version: 2022-11-28" \
-H "Content-Type: application/octet-stream" \
--data-binary "@-" \
"${GITHUB_UPLOAD_API}/${GITHUB_RELEASE_ID}/assets?name=${asset_name}&label=${asset_label}"
""",
returnStdout: true
).trim()
echo "GitHub UPLOAD ${asset_name} Release Asset Response: \n ${GITHUB_CREATE_RELEASE_RESPONSE}"
}
}
}
}
}
}
}