forked from aws-actions/aws-codebuild-run-build
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcode-build.js
454 lines (380 loc) · 11.7 KB
/
code-build.js
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
// Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: Apache-2.0
const core = require("@actions/core");
const aws = require("aws-sdk");
const assert = require("assert");
const NEW_INSTANCE_TAG = "CODEDEPLOY_TARGET";
const DEPLOYED_INSTANCE_TAG = "ACTIVE_API_INSTANCE";
module.exports = {
runDeploy,
deploy,
waitForBuildEndTime,
inputs2Parameters,
githubInputs,
buildSdk,
logName,
};
const branchOptions = {
master: {
applicationName: "InTeach-Academy",
deploymentGroupName: "Production-BlueGreen",
autoscalingGroupName: "academy",
newInstanceTag: NEW_INSTANCE_TAG,
deployedInstanceTag: DEPLOYED_INSTANCE_TAG,
},
doctolib: {
applicationName: "Doctolib",
deploymentGroupName: "Doctolib-BlueGreen",
autoscalingGroupName: "doctolib",
newInstanceTag: NEW_INSTANCE_TAG + "_DOCTOLIB",
deployedInstanceTag: DEPLOYED_INSTANCE_TAG + "_DOCTOLIB",
},
"feature/multibranch-deploy": {
applicationName: "Doctolib",
deploymentGroupName: "Doctolib-BlueGreen",
autoscalingGroupName: "doctolib",
newInstanceTag: NEW_INSTANCE_TAG + "_DOCTOLIB",
deployedInstanceTag: DEPLOYED_INSTANCE_TAG + "_DOCTOLIB",
},
};
async function runDeploy() {
// get a codeBuild instance from the SDK
const sdk = buildSdk();
// Get input options for startBuild
const inputs = githubInputs();
const opts = branchOptions[inputs.branchName] || branchOptions.master;
console.log("opts", opts);
const params = inputs2Parameters(inputs, opts);
console.log("params", JSON.stringify(params));
console.log("Deployment type is", inputs.deploymentType);
if (inputs.deploymentType === "in-place") {
return deploy(sdk, params);
} else {
console.log("Looking for ASG");
const autoscalingGroup = await getAutoScalingGroup(
opts.autoscalingGroupName
);
console.log("ASG found, scaling up");
const instanceId = await scale("UP", autoscalingGroup);
console.log(`Waiting for instance ${instanceId} to be ready`);
await waitFor(instanceId);
console.log(`Waiting for deployment on ${instanceId} to be done`);
await waitForDeployment(sdk, opts);
// Add tag to deploy to this new instance
console.log("Adding " + opts.newInstanceTag + " tag to instance");
await updateTags(instanceId, "target", opts);
/**
* We need to remove ASG from deployment group otherwise it will select
* the CODEDEPLOY_TARGET instance thus causing a crash because CD won't find
* a replacement. We will put it back after the deployment is successful
*/
//console.log("Removing ASG from Deployment Group");
//await updateDeploymentGroup(sdk, opts);
//console.log("Starting deployment with params", params);
//const deployInfos = await deploy(sdk, params);
//console.log("Adding ASG to Deployment Group");
//await updateDeploymentGroup(sdk, opts);
// Deploy successful now remove tag from ec2Instance
console.log("Updating tags");
await updateTags(instanceId, "", opts);
// Scaling down
console.log("Scaling down");
await scale("DOWN", autoscalingGroup);
return { status: "OK" };
}
}
async function waitForDeployment(sdk, opts) {
// Get current deployment
const {
deployments: [deploymentId],
} = await sdk.codeDeploy
.listDeployments({
applicationName: opts.applicationName,
deploymentGroupName: opts.deploymentGroupName,
includeOnlyStatuses: ["InProgress"],
})
.promise();
if (!deploymentId) {
console.log("No deployment in progress found");
return;
}
console.log(
`Deployment ${deploymentId} is in progress, wait for it to be done.`
);
await sdk.codeDeploy
.waitFor("deploymentSuccessful", {
deploymentId,
})
.promise();
}
/*async function updateDeploymentGroup(sdk, opts) {
await sdk.codeDeploy
.updateDeploymentGroup({
applicationName: opts.applicationName,
currentDeploymentGroupName: opts.deploymentGroupName,
autoScalingGroups: [],
ec2TagFilters: [
{
Key: opts.deployedInstanceTag,
Value: "",
Type: "KEY_ONLY",
},
],
})
.promise();
}*/
async function getAutoScalingGroup(autoscalingGroupName) {
const autoscaling = new aws.AutoScaling({ region: "eu-west-3" });
const {
AutoScalingGroups,
} = await autoscaling.describeAutoScalingGroups().promise();
const autoscalingGroup = AutoScalingGroups.find((group) =>
group.AutoScalingGroupName.toLowerCase().includes(autoscalingGroupName)
);
if (!autoscalingGroup) throw new Error("Autoscaling group not found");
return autoscalingGroup;
}
async function scale(direction, autoscalingGroup) {
const ec2 = new aws.EC2({ region: "eu-west-3" });
const autoscaling = new aws.AutoScaling({ region: "eu-west-3" });
const DesiredCapacity = direction === "UP" ? 2 : 1;
await autoscaling
.updateAutoScalingGroup({
DesiredCapacity,
AutoScalingGroupName: autoscalingGroup.AutoScalingGroupName,
})
.promise();
if (direction === "DOWN") return;
const TIMEOUT = 60; // 1 minute
const INTERVAL_TIME = 10 * 1000; // 10 Seconds
let totalTime = 0;
const InstanceId = await new Promise((resolve, reject) => {
const interval = setInterval(async () => {
if (totalTime / 1000 > TIMEOUT) {
clearInterval(interval);
return reject();
}
const { InstanceStatuses } = await ec2.describeInstanceStatus().promise();
const initializingInstance = InstanceStatuses.find(
({ InstanceStatus }) => {
return InstanceStatus.Details.find(({ Status }) => {
return Status === "initializing";
});
}
);
if (initializingInstance) {
clearInterval(interval);
return resolve(initializingInstance.InstanceId);
}
totalTime += INTERVAL_TIME;
}, INTERVAL_TIME);
});
return InstanceId;
}
async function updateTags(InstanceId, typeOfTag, opts) {
const ec2 = new aws.EC2({ region: "eu-west-3" });
if (typeOfTag === "target") {
await ec2
.createTags({
Resources: [InstanceId],
Tags: [{ Key: opts.newInstanceTag, Value: "" }],
})
.promise();
} else {
await Promise.all([
ec2
.deleteTags({
Resources: [InstanceId],
Tags: [
{
Key: opts.newInstanceTag,
},
],
})
.promise(),
ec2
.createTags({
Resources: [InstanceId],
Tags: [{ Key: opts.deployedInstanceTag, Value: "" }],
})
.promise(),
]);
}
}
async function waitFor(InstanceId) {
const ec2 = new aws.EC2({ region: "eu-west-3" });
const TIMEOUT = 300;
const INTERVAL_TIME = 10 * 1000;
let totalTime = 0;
await new Promise((resolve, reject) => {
const interval = setInterval(async () => {
if (totalTime / 1000 > TIMEOUT) {
clearInterval(interval);
return reject();
}
const status = await ec2
.describeInstanceStatus({
InstanceIds: [InstanceId],
})
.promise();
const InstanceStatus =
status.InstanceStatuses[0] &&
status.InstanceStatuses[0].InstanceStatus &&
status.InstanceStatuses[0].InstanceStatus.Status;
if (InstanceStatus === "ok") {
clearInterval(interval);
return resolve();
}
totalTime += INTERVAL_TIME;
}, INTERVAL_TIME);
});
}
async function deploy(sdk, params) {
// Start the deployment
const deployment = await sdk.codeDeploy.createDeployment(params).promise();
// Wait for the deployment to be "TODO"
return waitForBuildEndTime(sdk, deployment.deploymentId);
}
async function waitForBuildEndTime(sdk, deploymentId) {
const { codeDeploy, wait = 1000 * 30, backOff = 1000 * 15 } = sdk;
// Get deployment status
const deploymentStatus = await codeDeploy
.getDeployment({ deploymentId })
.promise();
const status = deploymentStatus.deploymentInfo.status;
const overview = deploymentStatus.deploymentInfo.deploymentOverview;
const ongoingStatus = ["Created", "Queued", "InProgress", "Ready"];
// Check if it's successful
if (status === "Succeeded") {
console.log(`[${status}] : `, overview);
return {
status,
overview,
deploymentId,
};
}
// Check if it's ongoing
if (ongoingStatus.includes(status)) {
console.log(`[${status}] : `, overview);
const newWait = wait + backOff;
//Sleep before trying again
await new Promise((resolve) => setTimeout(resolve, newWait));
// Try again from the same token position
return waitForBuildEndTime({ ...sdk, wait: newWait }, deploymentId);
}
console.log("deploymentStatus", deploymentStatus);
// Now there is an error
throw new Error({
deploymentId,
code: deploymentStatus.errorInformation.code,
message: deploymentStatus.errorInformation.message,
});
}
function githubInputs() {
const applicationName = core.getInput("application-name", { required: true });
const deploymentConfigName = core.getInput("deployment-config-name", {
required: true,
});
const deploymentGroupName = core.getInput("deployment-group-name", {
required: true,
});
const fileExistsBehavior = core.getInput("file-exists-behavior", {
required: false,
});
const s3Bucket = core.getInput("s3-bucket");
const s3Key = core.getInput("s3-key");
const bundleType = core.getInput("bundle-type");
const deploymentType = core.getInput("deployment-type");
const branchName = core.getInput("branch-name");
return {
applicationName,
deploymentConfigName,
deploymentGroupName,
fileExistsBehavior,
s3Bucket,
s3Key,
bundleType,
deploymentType,
branchName,
};
}
function inputs2Parameters(inputs, opts) {
const {
deploymentConfigName,
fileExistsBehavior = "DISALLOW",
s3Bucket,
s3Key,
bundleType = "zip",
deploymentType,
} = inputs;
const mainConfig = {
applicationName: opts.applicationName,
autoRollbackConfiguration: {
enabled: true,
events: ["DEPLOYMENT_FAILURE", "DEPLOYMENT_STOP_ON_REQUEST"],
},
deploymentConfigName,
fileExistsBehavior,
ignoreApplicationStopFailures: true,
deploymentGroupName: opts.deploymentGroupName,
revision: {
revisionType: "S3",
s3Location: {
bucket: s3Bucket,
bundleType,
key: s3Key,
},
},
};
if (deploymentType === "blue-green") {
return {
...mainConfig,
targetInstances: {
ec2TagSet: {
ec2TagSetList: [
[
{
Key: opts.newInstanceTag,
Value: "",
Type: "KEY_ONLY",
},
],
],
},
},
};
}
return mainConfig;
}
function buildSdk({ local = false } = {}) {
if (local) {
const profile = new aws.SharedIniFileCredentials({
profile: "academy-api-deploy",
});
aws.config.credentials = profile;
}
const codeDeploy = new aws.CodeDeploy({
customUserAgent: "aws-actions/aws-codedeploy-run-build",
region: "eu-west-3",
});
const autoScaling = new aws.AutoScaling({
customUserAgent: "aws-actions/aws-codedeploy-run-build",
region: "eu-west-3",
});
assert(
codeDeploy.config.credentials,
"No credentials. Try adding @aws-actions/configure-aws-credentials earlier in your job to set up AWS credentials."
);
return { codeDeploy, autoScaling };
}
function logName(Arn) {
const [logGroupName, logStreamName] = Arn.split(":log-group:")
.pop()
.split(":log-stream:");
if (logGroupName === "null" || logStreamName === "null")
return {
logGroupName: undefined,
logStreamName: undefined,
};
return { logGroupName, logStreamName };
}