-
Notifications
You must be signed in to change notification settings - Fork 44
/
Jenkinsfile
320 lines (292 loc) · 9.61 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
#!groovy
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
node {
checkout()
build()
putBinary()
buildInfrastructure()
}
def checkout() {
stage('Clone') {
git branch: 'master', url: 'https://github.com/kevincloud/javaperks-customer-api.git'
}
}
def build() {
stage('Build') {
mvn 'package'
}
}
def putBinary() {
stage('Upload Binary') {
def fileName = ""
def fullPath = ""
Collection<org.jenkinsci.plugins.pipeline.maven.MavenArtifact> generatedArtifacts = currentBuild.rawBuild.getAction(org.jenkinsci.plugins.pipeline.maven.publishers.MavenReport.class).getGeneratedArtifacts();
for (org.jenkinsci.plugins.pipeline.maven.MavenArtifact generatedArtifact:generatedArtifacts) {
fileName = generatedArtifact.getFileName();
println(fileName)
println("--------")
break
}
// TODO: Fix region
fullPath = env.WORKSPACE + "/target/" + fileName
// withAWS(credentials:'pipeline-credentials', region: env.AWS_REGION) {
// s3Upload(bucket: env.ASSET_BUCKET, file: fullPath, path: fileName)
// }
withAWS(region: env.AWS_REGION) {
s3Upload(bucket: env.ASSET_BUCKET, file: fullPath, path: fileName)
}
}
}
def buildInfrastructure() {
stage('Run Terraform') {
def runid = ""
getWorkspaceId()
buildPayload()
runid = startPlan()
waitForPlan(runid)
}
}
def getWorkspaceId() {
def response = httpRequest(
customHeaders: [
[ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ],
[ name: "Content-Type", value: "application/vnd.api+json" ]
],
url: "https://app.terraform.io/api/v2/organizations/" + env.TF_ORGNAME + "/workspaces/" + env.TF_WORKSPACE
)
def data = new JsonSlurper().parseText(response.content)
println ("Workspace Id: " + data.data.id)
return data.data.id
}
def buildPayload() {
def wsid = getWorkspaceId()
def payload = """
{
"data": {
"attributes": {
"is-destroy":false,
"message": "Triggered run from Jenkins (build #${env.BUILD_NUMBER})"
},
"type":"runs",
"relationships": {
"workspace": {
"data": {
"type": "workspaces",
"id": "${wsid}"
}
}
}
}
}
"""
return payload
}
def startPlan() {
def payload = buildPayload()
def response = httpRequest(
customHeaders: [
[ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ],
[ name: "Content-Type", value: "application/vnd.api+json" ]
],
httpMode: 'POST',
requestBody: "${payload}",
url: "https://app.terraform.io/api/v2/runs"
)
def data = new JsonSlurper().parseText(response.content)
println ("Run Id: " + data.data.id)
return data.data.id
}
def waitForPlan(runid) {
def count = 0
while (true) {
def status = getPlanStatus(runid)
println("Status: " + status)
// If a policy requires an override, prompt in the pipeline
if (status.startsWith("approve_policy")) {
def override
try {
override = input (message: 'Override policy?',
ok: 'Continue',
parameters: [ booleanParam(
defaultValue: false,
description: 'A policy restriction is enforced on this workspace. Check the box to approve overriding the policy.',
name: 'Override')
])
} catch (err) {
override = false
}
// If we're overriding, tell terraform. Otherwise, discard the run
if (override == true) {
println('Overriding!')
def item = status.split(':')[1]
def overridden = overridePolicy(item)
if (!overridden) {
println("Could not override the policy")
discardRun(runid)
error("Could not override the Sentinel policy")
break
}
} else {
println('Rejecting!')
discardRun(runid)
error("The pipeline failed due to a Sentinel policy restriction.")
break
}
}
// If we're ready to apply, prompt in the pipeline to do so
if (status == "apply_plan") {
def apply
try {
apply = input (message: 'Confirm Apply', ok: 'Continue',
parameters: [booleanParam(defaultValue: false,
description: 'Would you like to continue to apply this run?', name: 'Apply')])
} catch (err) {
apply = false
}
// If we're going to apply, tell Terraform. Otherwise, discard the run
if (apply == true) {
println('Applying plan')
applyRun(runid)
}
else {
println('Rejecting!')
discardRun(runid)
error("The pipeline failed due to a manual rejection of the plan.")
break
}
}
if (count > 60) break
count++
sleep(2)
}
}
def waitforApply(runid) {
def count = 0
while (true) {
def status = getApplyStatus(runid)
println("Status: " + status)
if (status == 'discarded') {
println("This run has been discarded")
error("The Terraform run has been discarded, and the pipeline cannot continue.")
break
}
if (status == 'canceled') {
println("This run has been canceled outside the pipeline")
error("The Terraform run has been canceled outside the pipeline, and the pipeline cannot continue.")
break
}
if (status == 'errored') {
println("This run has encountered an error while applying")
error("The Terraform run has encountered an error while applying, and the pipeline cannot continue.")
break
}
if (status == 'applied') {
println("This run has finished applying")
break
}
if (count > 60) break
count++
sleep(2)
}
}
def applyRun(runid) {
def response = httpRequest(
customHeaders: [
[ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ],
[ name: "Content-Type", value: "application/vnd.api+json" ]
],
httpMode: 'POST',
responseBody: '{ comment: "Apply confirmed" }',
url: "https://app.terraform.io/api/v2/runs/${runid}/actions/apply"
)
}
def discardRun(runid) {
def response = httpRequest(
customHeaders: [
[ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ],
[ name: "Content-Type", value: "application/vnd.api+json" ]
],
httpMode: 'POST',
responseBody: '{ comment: "Run has been discarded" }',
url: "https://app.terraform.io/api/v2/runs/${runid}/actions/discard"
)
}
def overridePolicy(policyid) {
def response = httpRequest(
customHeaders: [
[ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ],
[ name: "Content-Type", value: "application/vnd.api+json" ]
],
httpMode: 'POST',
url: "https://app.terraform.io/api/v2/policy-checks/${policyid}/actions/override"
)
def data = new JsonSlurper().parseText(response.content)
if (data.data.attributes.status != "overridden") {
return false
}
else {
return true
}
}
def getPlanStatus(runid) {
def result = ""
def response = httpRequest(
customHeaders: [[ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ]],
url: "https://app.terraform.io/api/v2/runs/${runid}"
)
def data = new JsonSlurper().parseText(response.content)
switch (data.data.attributes.status) {
case 'pending':
case 'plan_queued':
result = "pending"
break
case 'planning':
result = "planning"
break
case 'planned':
result = "planned"
break
case 'cost_estimating':
case 'cost_estimated':
result = "costing"
break
case 'policy_checking':
result = "policy"
break
case 'policy_override':
println(response.content)
result = "approve_policy:" + data.data.relationships["policy-checks"].data[0].id
break
case 'policy_checked':
result = "apply_plan"
break
default:
result = "running"
break
}
return result
}
def getApplyStatus(runid) {
def result = ""
def response = httpRequest(
customHeaders: [[ name: "Authorization", value: "Bearer " + env.BEARER_TOKEN ]],
url: "https://app.terraform.io/api/v2/runs/${runid}"
)
def data = new JsonSlurper().parseText(response.content)
switch (data.data.attributes.status) {
case 'discarded':
case 'errored':
case 'canceled':
result = data.data.attributes.status
break
default:
result = "pending"
}
return result
}
def mvn(args) {
withMaven() {
sh "mvn $args"
}
}