-
Notifications
You must be signed in to change notification settings - Fork 266
Expand file tree
/
Copy pathindex.js
More file actions
706 lines (601 loc) · 27.2 KB
/
index.js
File metadata and controls
706 lines (601 loc) · 27.2 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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
const path = require('path');
const core = require('@actions/core');
const { CodeDeploy, waitUntilDeploymentSuccessful } = require('@aws-sdk/client-codedeploy');
const { ECS, waitUntilServicesStable, waitUntilTasksStopped } = require('@aws-sdk/client-ecs');
const yaml = require('yaml');
const fs = require('fs');
const crypto = require('crypto');
const MAX_WAIT_MINUTES = 360; // 6 hours
const WAIT_DEFAULT_DELAY_SEC = 15;
// Attributes that are returned by DescribeTaskDefinition, but are not valid RegisterTaskDefinition inputs
const IGNORED_TASK_DEFINITION_ATTRIBUTES = [
'compatibilities',
'taskDefinitionArn',
'requiresAttributes',
'revision',
'status',
'registeredAt',
'deregisteredAt',
'registeredBy'
];
// Method to run a stand-alone task with desired inputs
async function runTask(ecs, clusterName, taskDefArn, waitForMinutes, enableECSManagedTags, waitMaxDelaySeconds) {
core.info('Running task')
const waitForTask = core.getInput('wait-for-task-stopped', { required: false }) || 'false';
const startedBy = core.getInput('run-task-started-by', { required: false }) || 'GitHub-Actions';
const launchType = core.getInput('run-task-launch-type', { required: false }) || 'FARGATE';
const subnetIds = core.getInput('run-task-subnets', { required: false }) || '';
const securityGroupIds = core.getInput('run-task-security-groups', { required: false }) || '';
const containerOverrides = JSON.parse(core.getInput('run-task-container-overrides', { required: false }) || '[]');
const assignPublicIP = core.getInput('run-task-assign-public-IP', { required: false }) || 'DISABLED';
const tags = JSON.parse(core.getInput('run-task-tags', { required: false }) || '[]');
const capacityProviderStrategy = JSON.parse(core.getInput('run-task-capacity-provider-strategy', { required: false }) || '[]');
const runTaskManagedEBSVolumeName = core.getInput('run-task-managed-ebs-volume-name', { required: false }) || '';
const runTaskManagedEBSVolume = core.getInput('run-task-managed-ebs-volume', { required: false }) || '{}';
let awsvpcConfiguration = {}
if (subnetIds != "") {
awsvpcConfiguration["subnets"] = subnetIds.split(',')
}
if (securityGroupIds != "") {
awsvpcConfiguration["securityGroups"] = securityGroupIds.split(',')
}
if(assignPublicIP != "" && (subnetIds != "" || securityGroupIds != "")){
awsvpcConfiguration["assignPublicIp"] = assignPublicIP
}
let volumeConfigurations = [];
let taskManagedEBSVolumeObject;
if (runTaskManagedEBSVolumeName != '') {
if (runTaskManagedEBSVolume != '{}') {
taskManagedEBSVolumeObject = convertToManagedEbsVolumeObject(runTaskManagedEBSVolume);
volumeConfigurations = [{
name: runTaskManagedEBSVolumeName,
managedEBSVolume: taskManagedEBSVolumeObject
}];
} else {
core.warning(`run-task-managed-ebs-volume-name provided without run-task-managed-ebs-volume value. VolumeConfigurations property will not be included in the RunTask API call`);
}
}
const runTaskResponse = await ecs.runTask({
startedBy: startedBy,
cluster: clusterName,
taskDefinition: taskDefArn,
overrides: {
containerOverrides: containerOverrides
},
capacityProviderStrategy: capacityProviderStrategy.length === 0 ? null : capacityProviderStrategy,
launchType: capacityProviderStrategy.length === 0 ? launchType : null,
networkConfiguration: Object.keys(awsvpcConfiguration).length === 0 ? null : { awsvpcConfiguration: awsvpcConfiguration },
enableECSManagedTags: enableECSManagedTags,
tags: tags,
volumeConfigurations: volumeConfigurations
});
core.debug(`Run task response ${JSON.stringify(runTaskResponse)}`)
const taskArns = runTaskResponse.tasks.map(task => task.taskArn);
core.setOutput('run-task-arn', taskArns);
const region = await ecs.config.region();
const consoleHostname = region.startsWith('cn') ? 'console.amazonaws.cn' : 'console.aws.amazon.com';
core.info(`Task running: https://${consoleHostname}/ecs/home?region=${region}#/clusters/${clusterName}/tasks`);
if (runTaskResponse.failures && runTaskResponse.failures.length > 0) {
const failure = runTaskResponse.failures[0];
throw new Error(`${failure.arn} is ${failure.reason}`);
}
// Wait for task to end
if (waitForTask && waitForTask.toLowerCase() === "true") {
await waitForTasksStopped(ecs, clusterName, taskArns, waitForMinutes, waitMaxDelaySeconds)
await tasksExitCode(ecs, clusterName, taskArns)
} else {
core.debug('Not waiting for the task to stop');
}
}
function convertToManagedEbsVolumeObject(managedEbsVolume) {
managedEbsVolumeObject = {}
const ebsVolumeObject = JSON.parse(managedEbsVolume);
if ('roleArn' in ebsVolumeObject){ // required property
managedEbsVolumeObject.roleArn = ebsVolumeObject.roleArn;
core.debug(`Found RoleArn ${ebsVolumeObject['roleArn']}`);
} else {
throw new Error('managed-ebs-volume must provide "role-arn" to associate with the EBS volume')
}
if ('encrypted' in ebsVolumeObject) {
managedEbsVolumeObject.encrypted = ebsVolumeObject.encrypted;
}
if ('filesystemType' in ebsVolumeObject) {
managedEbsVolumeObject.filesystemType = ebsVolumeObject.filesystemType;
}
if ('iops' in ebsVolumeObject) {
managedEbsVolumeObject.iops = ebsVolumeObject.iops;
}
if ('kmsKeyId' in ebsVolumeObject) {
managedEbsVolumeObject.kmsKeyId = ebsVolumeObject.kmsKeyId;
}
if ('sizeInGiB' in ebsVolumeObject) {
managedEbsVolumeObject.sizeInGiB = ebsVolumeObject.sizeInGiB;
}
if ('snapshotId' in ebsVolumeObject) {
managedEbsVolumeObject.snapshotId = ebsVolumeObject.snapshotId;
}
if ('tagSpecifications' in ebsVolumeObject) {
managedEbsVolumeObject.tagSpecifications = ebsVolumeObject.tagSpecifications;
}
if (('throughput' in ebsVolumeObject) && (('volumeType' in ebsVolumeObject) && (ebsVolumeObject.volumeType == 'gp3'))){
managedEbsVolumeObject.throughput = ebsVolumeObject.throughput;
}
if ('volumeType' in ebsVolumeObject) {
managedEbsVolumeObject.volumeType = ebsVolumeObject.volumeType;
}
core.debug(`Created managedEbsVolumeObject: ${JSON.stringify(managedEbsVolumeObject)}`);
return managedEbsVolumeObject;
}
// Poll tasks until they enter a stopped state
async function waitForTasksStopped(ecs, clusterName, taskArns, waitForMinutes, waitMaxDelaySeconds) {
if (waitForMinutes > MAX_WAIT_MINUTES) {
waitForMinutes = MAX_WAIT_MINUTES;
}
core.info(`Waiting for tasks to stop. Will wait for ${waitForMinutes} minutes`);
const waiterConfig = {
client: ecs,
minDelay: WAIT_DEFAULT_DELAY_SEC,
maxWaitTime: waitForMinutes * 60,
};
if (waitMaxDelaySeconds) {
waiterConfig.maxDelay = waitMaxDelaySeconds;
}
const waitTaskResponse = await waitUntilTasksStopped(waiterConfig, {
cluster: clusterName,
tasks: taskArns,
});
core.debug(`Run task response ${JSON.stringify(waitTaskResponse)}`);
core.info('All tasks have stopped.');
}
// Check a task's exit code and fail the job on error
async function tasksExitCode(ecs, clusterName, taskArns) {
const describeResponse = await ecs.describeTasks({
cluster: clusterName,
tasks: taskArns
});
const containers = [].concat(...describeResponse.tasks.map(task => task.containers))
const exitCodes = containers.map(container => container.exitCode)
const reasons = containers.map(container => container.reason)
const failuresIdx = [];
exitCodes.filter((exitCode, index) => {
if (exitCode !== 0) {
failuresIdx.push(index)
}
})
const failures = reasons.filter((_, index) => failuresIdx.indexOf(index) !== -1)
if (failures.length > 0) {
throw new Error(`Run task failed: ${JSON.stringify(failures)}`);
}
}
// Deploy to a service that uses the 'ECS' deployment controller
async function updateEcsService(ecs, clusterName, service, taskDefArn, waitForService, waitForMinutes, forceNewDeployment, desiredCount, enableECSManagedTags, propagateTags, waitMaxDelaySeconds) {
core.debug('Updating the service');
const serviceManagedEBSVolumeName = core.getInput('service-managed-ebs-volume-name', { required: false }) || '';
const serviceManagedEBSVolume = core.getInput('service-managed-ebs-volume', { required: false }) || '{}';
let volumeConfigurations = [];
let serviceManagedEbsVolumeObject;
if (serviceManagedEBSVolumeName != '') {
if (serviceManagedEBSVolume != '{}') {
serviceManagedEbsVolumeObject = convertToManagedEbsVolumeObject(serviceManagedEBSVolume);
volumeConfigurations = [{
name: serviceManagedEBSVolumeName,
managedEBSVolume: serviceManagedEbsVolumeObject
}];
} else {
core.warning('service-managed-ebs-volume-name provided without service-managed-ebs-volume value. VolumeConfigurations property will not be included in the UpdateService API call');
}
}
let params = {
cluster: clusterName,
service: service,
taskDefinition: taskDefArn,
forceNewDeployment: forceNewDeployment,
enableECSManagedTags: enableECSManagedTags,
propagateTags: propagateTags,
volumeConfigurations: volumeConfigurations
};
// Add the desiredCount property only if it is defined and a number.
if (!isNaN(desiredCount) && desiredCount !== undefined) {
params.desiredCount = desiredCount;
}
await ecs.updateService(params);
const region = await ecs.config.region();
const consoleHostname = region.startsWith('cn') ? 'console.amazonaws.cn' : 'console.aws.amazon.com';
core.info(`Deployment started. Watch this deployment's progress in the Amazon ECS console: https://${region}.${consoleHostname}/ecs/v2/clusters/${clusterName}/services/${service}/deployments?region=${region}`);
// Wait for service stability
if (waitForService && waitForService.toLowerCase() === 'true') {
core.debug(`Waiting for the service to become stable. Will wait for ${waitForMinutes} minutes`);
const waiterConfig = {
client: ecs,
minDelay: WAIT_DEFAULT_DELAY_SEC,
maxWaitTime: waitForMinutes * 60
};
if (waitMaxDelaySeconds) {
waiterConfig.maxDelay = waitMaxDelaySeconds;
}
await waitUntilServicesStable(waiterConfig, {
services: [service],
cluster: clusterName
});
await verifyServiceDeployment(ecs, clusterName, service, taskDefArn);
} else {
core.debug('Not waiting for the service to become stable');
}
}
async function verifyServiceDeployment(ecs, clusterName, serviceName, expectedTaskDefArn) {
core.debug(
`Verifying that service '${serviceName}' stabilized on expected task definition '${expectedTaskDefArn}'`
);
// Describe the service after the waiter reports "stable".
// This extra check is necessary because ECS can become stable again
// by rolling back to the previous deployment if circuit breaker
// rollback is enabled.
const describeResponse = await ecs.describeServices({
cluster: clusterName,
services: [serviceName]
});
// Surface any ECS-level lookup failures explicitly.
const failures = describeResponse.failures || [];
if (failures.length > 0) {
const failure = failures[0];
throw new Error(
`Failed to describe service '${serviceName}': ${failure.reason || 'unknown error'}`
);
}
// We expect exactly one service back because we queried by name.
const service = describeResponse.services && describeResponse.services[0];
if (!service) {
throw new Error(`Service '${serviceName}' was not returned by DescribeServices`);
}
const deployments = service.deployments || [];
// Find the deployment created from the task definition revision
// we just deployed.
const expectedDeployment = deployments.find(
deployment => deployment.taskDefinition === expectedTaskDefArn
);
// Find the deployment ECS considers PRIMARY after stabilization.
// This is the deployment currently serving traffic / considered active.
const primaryDeployment = deployments.find(
deployment => deployment.status === 'PRIMARY'
);
// If ECS explicitly marks the expected deployment as FAILED,
// fail immediately and include the AWS reason when available.
if (expectedDeployment && expectedDeployment.rolloutState === 'FAILED') {
const reason = expectedDeployment.rolloutStateReason
? ` Reason: ${expectedDeployment.rolloutStateReason}`
: '';
throw new Error(
`ECS deployment failed for task definition '${expectedTaskDefArn}'.${reason}`
);
}
// PRIMARY should always exist for a healthy service state.
if (!primaryDeployment) {
throw new Error(`No PRIMARY deployment found for service '${serviceName}'`);
}
// This is the key rollback check:
// even if the service is "stable", ECS may have rolled back to the
// previous task definition. In that case, the PRIMARY deployment
// will not match the task definition we expected to promote.
if (primaryDeployment.taskDefinition !== expectedTaskDefArn) {
throw new Error(
`ECS deployment did not complete on the expected task definition. ` +
`Expected PRIMARY task definition '${expectedTaskDefArn}', but found ` +
`'${primaryDeployment.taskDefinition}'. This usually means ECS rolled back ` +
`after the new deployment failed.`
);
}
// When rolloutState is available, require the expected deployment
// to have fully completed, not merely exist.
// This is an additional safeguard on top of the PRIMARY check.
if (
expectedDeployment &&
expectedDeployment.rolloutState &&
expectedDeployment.rolloutState !== 'COMPLETED'
) {
throw new Error(
`ECS deployment for task definition '${expectedTaskDefArn}' did not reach ` +
`COMPLETED. Current rolloutState: '${expectedDeployment.rolloutState}'.`
);
}
core.info(
`Deployment verified: service '${serviceName}' is PRIMARY on expected task definition.`
);
}
// Find value in a CodeDeploy AppSpec file with a case-insensitive key
function findAppSpecValue(obj, keyName) {
return obj[findAppSpecKey(obj, keyName)];
}
function findAppSpecKey(obj, keyName) {
if (!obj) {
throw new Error(`AppSpec file must include property '${keyName}'`);
}
const keyToMatch = keyName.toLowerCase();
for (var key in obj) {
if (key.toLowerCase() == keyToMatch) {
return key;
}
}
throw new Error(`AppSpec file must include property '${keyName}'`);
}
// Accepts an optional set of keys to keep even if their value is null or empty string
function isEmptyValue(value, key, keepNullValueKeysSet) {
// If key is in keepNullValueKeysSet, do not treat as empty
if (keepNullValueKeysSet && key && keepNullValueKeysSet.has(key)) {
return false;
}
if (value === null || value === undefined || value === '') {
return true;
}
if (Array.isArray(value)) {
for (var element of value) {
if (!isEmptyValue(element, undefined, keepNullValueKeysSet)) {
// the array has at least one non-empty element
return false;
}
}
// the array has no non-empty elements
return true;
}
if (typeof value === 'object') {
for (var childValue of Object.values(value)) {
if (!isEmptyValue(childValue)) {
// the object has at least one non-empty property
return false;
}
}
// the object has no non-empty property
return true;
}
return false;
}
// Accepts keepNullValueKeysSet as closure
function makeEmptyValueReplacer(keepNullValueKeysSet) {
return function emptyValueReplacer(key, value) {
if (isEmptyValue(value, key, keepNullValueKeysSet)) {
return undefined;
}
if (Array.isArray(value)) {
return value.filter(e => !isEmptyValue(e, undefined, keepNullValueKeysSet));
}
return value;
};
}
// Accepts an optional array of keys to keep if null/empty
function cleanNullKeys(obj, keepNullValueKeys) {
let keepNullValueKeysSet = null;
if (Array.isArray(keepNullValueKeys) && keepNullValueKeys.length > 0) {
keepNullValueKeysSet = new Set(keepNullValueKeys);
}
return JSON.parse(JSON.stringify(obj, makeEmptyValueReplacer(keepNullValueKeysSet)));
}
function removeIgnoredAttributes(taskDef) {
for (var attribute of IGNORED_TASK_DEFINITION_ATTRIBUTES) {
if (taskDef[attribute]) {
core.warning(`Ignoring property '${attribute}' in the task definition file. ` +
'This property is returned by the Amazon ECS DescribeTaskDefinition API and may be shown in the ECS console, ' +
'but it is not a valid field when registering a new task definition. ' +
'This field can be safely removed from your task definition file.');
delete taskDef[attribute];
}
}
return taskDef;
}
function maintainValidObjects(taskDef) {
if (validateProxyConfigurations(taskDef)) {
taskDef.proxyConfiguration.properties.forEach((property, index, arr) => {
if (!('value' in property)) {
arr[index].value = '';
}
if (!('name' in property)) {
arr[index].name = '';
}
});
}
if(taskDef && taskDef.containerDefinitions){
taskDef.containerDefinitions.forEach((container) => {
if(container.environment){
container.environment.forEach((property, index, arr) => {
if (!('value' in property)) {
arr[index].value = '';
}
});
}
});
}
return taskDef;
}
function validateProxyConfigurations(taskDef){
return 'proxyConfiguration' in taskDef && taskDef.proxyConfiguration.type && taskDef.proxyConfiguration.type == 'APPMESH' && taskDef.proxyConfiguration.properties && taskDef.proxyConfiguration.properties.length > 0;
}
// Deploy to a service that uses the 'CODE_DEPLOY' deployment controller
async function createCodeDeployDeployment(codedeploy, clusterName, service, taskDefArn, waitForService, waitForMinutes, waitMaxDelaySeconds) {
core.debug('Updating AppSpec file with new task definition ARN');
let codeDeployAppSpecFile = core.getInput('codedeploy-appspec', { required : false });
codeDeployAppSpecFile = codeDeployAppSpecFile ? codeDeployAppSpecFile : 'appspec.yaml';
let codeDeployApp = core.getInput('codedeploy-application', { required: false });
codeDeployApp = codeDeployApp ? codeDeployApp : `AppECS-${clusterName}-${service}`;
let codeDeployGroup = core.getInput('codedeploy-deployment-group', { required: false });
codeDeployGroup = codeDeployGroup ? codeDeployGroup : `DgpECS-${clusterName}-${service}`;
let codeDeployDescription = core.getInput('codedeploy-deployment-description', { required: false });
let codeDeployConfig = core.getInput('codedeploy-deployment-config', { required: false });
let deploymentGroupDetails = await codedeploy.getDeploymentGroup({
applicationName: codeDeployApp,
deploymentGroupName: codeDeployGroup
});
deploymentGroupDetails = deploymentGroupDetails.deploymentGroupInfo;
// Insert the task def ARN into the appspec file
const appSpecPath = path.isAbsolute(codeDeployAppSpecFile) ?
codeDeployAppSpecFile :
path.join(process.env.GITHUB_WORKSPACE, codeDeployAppSpecFile);
const fileContents = fs.readFileSync(appSpecPath, 'utf8');
const appSpecContents = yaml.parse(fileContents);
for (var resource of findAppSpecValue(appSpecContents, 'resources')) {
for (var name in resource) {
const resourceContents = resource[name];
const properties = findAppSpecValue(resourceContents, 'properties');
const taskDefKey = findAppSpecKey(properties, 'taskDefinition');
properties[taskDefKey] = taskDefArn;
}
}
const appSpecString = JSON.stringify(appSpecContents);
const appSpecHash = crypto.createHash('sha256').update(appSpecString).digest('hex');
// Start the deployment with the updated appspec contents
core.debug('Starting CodeDeploy deployment');
let deploymentParams = {
applicationName: codeDeployApp,
deploymentGroupName: codeDeployGroup,
revision: {
revisionType: 'AppSpecContent',
appSpecContent: {
content: appSpecString,
sha256: appSpecHash
}
}
};
// If it hasn't been set then we don't even want to pass it to the api call to maintain previous behaviour.
if (codeDeployDescription) {
// CodeDeploy Deployment Descriptions have a max length of 512 characters, so truncate if necessary
deploymentParams.description = (codeDeployDescription.length <= 512) ? codeDeployDescription : `${codeDeployDescription.substring(0,511)}…`;
}
if (codeDeployConfig) {
deploymentParams.deploymentConfigName = codeDeployConfig
}
const createDeployResponse = await codedeploy.createDeployment(deploymentParams);
core.setOutput('codedeploy-deployment-id', createDeployResponse.deploymentId);
const region = await codedeploy.config.region();
core.info(`Deployment started. Watch this deployment's progress in the AWS CodeDeploy console: https://console.aws.amazon.com/codesuite/codedeploy/deployments/${createDeployResponse.deploymentId}?region=${region}`);
// Wait for deployment to complete
if (waitForService && waitForService.toLowerCase() === 'true') {
// Determine wait time
const deployReadyWaitMin = deploymentGroupDetails.blueGreenDeploymentConfiguration.deploymentReadyOption.waitTimeInMinutes;
const terminationWaitMin = deploymentGroupDetails.blueGreenDeploymentConfiguration.terminateBlueInstancesOnDeploymentSuccess.terminationWaitTimeInMinutes;
let totalWaitMin = deployReadyWaitMin + terminationWaitMin + waitForMinutes;
if (totalWaitMin > MAX_WAIT_MINUTES) {
totalWaitMin = MAX_WAIT_MINUTES;
}
core.debug(`Waiting for the deployment to complete. Will wait for ${totalWaitMin} minutes`);
const waiterConfig = {
client: codedeploy,
minDelay: WAIT_DEFAULT_DELAY_SEC,
maxWaitTime: totalWaitMin * 60
};
if (waitMaxDelaySeconds) {
waiterConfig.maxDelay = waitMaxDelaySeconds;
}
await waitUntilDeploymentSuccessful(waiterConfig, {
deploymentId: createDeployResponse.deploymentId
});
} else {
core.debug('Not waiting for the deployment to complete');
}
}
async function run() {
try {
// Get inputs
const taskDefinitionFile = core.getInput('task-definition', { required: true });
const service = core.getInput('service', { required: false });
const cluster = core.getInput('cluster', { required: false });
const maxRetries = parseInt(core.getInput('max-retries', { required: false })) || 3;
const waitForService = core.getInput('wait-for-service-stability', { required: false });
let waitForMinutes = parseInt(core.getInput('wait-for-minutes', { required: false })) || 30;
if (waitForMinutes > MAX_WAIT_MINUTES) {
waitForMinutes = MAX_WAIT_MINUTES;
}
const waitMaxDelaySecondsInput = core.getInput('wait-max-delay-seconds', { required: false });
const waitMaxDelaySeconds = waitMaxDelaySecondsInput ? parseInt(waitMaxDelaySecondsInput) : null;
const forceNewDeployInput = core.getInput('force-new-deployment', { required: false }) || 'false';
const forceNewDeployment = forceNewDeployInput.toLowerCase() === 'true';
const desiredCount = parseInt((core.getInput('desired-count', {required: false})));
const enableECSManagedTagsInput = core.getInput('enable-ecs-managed-tags', { required: false }) || '';
let enableECSManagedTags = null;
if (enableECSManagedTagsInput !== '') {
enableECSManagedTags = enableECSManagedTagsInput.toLowerCase() === 'true';
}
const propagateTagsInput = core.getInput('propagate-tags', { required: false }) || '';
let propagateTags = null;
if (propagateTagsInput !== '') {
propagateTags = propagateTagsInput;
}
// Get keep-null-value-keys input comma-separated
let keepNullValueKeysInput = core.getInput('keep-null-value-keys', { required: false }) || '';
let keepNullValueKeys = [];
if (keepNullValueKeysInput) {
keepNullValueKeys = keepNullValueKeysInput.split(',').map(k => k.trim()).filter(Boolean);
}
const ecs = new ECS({
customUserAgent: 'amazon-ecs-deploy-task-definition-for-github-actions',
maxAttempts: maxRetries,
retryMode: 'standard'
});
const codedeploy = new CodeDeploy({
customUserAgent: 'amazon-ecs-deploy-task-definition-for-github-actions',
maxAttempts: maxRetries,
retryMode: 'standard'
});
// Register the task definition
core.debug('Registering the task definition');
const taskDefPath = path.isAbsolute(taskDefinitionFile) ?
taskDefinitionFile :
path.join(process.env.GITHUB_WORKSPACE, taskDefinitionFile);
const fileContents = fs.readFileSync(taskDefPath, 'utf8');
const taskDefContents = maintainValidObjects(removeIgnoredAttributes(cleanNullKeys(yaml.parse(fileContents), keepNullValueKeys)));
let registerResponse;
try {
registerResponse = await ecs.registerTaskDefinition(taskDefContents);
} catch (error) {
core.setFailed("Failed to register task definition in ECS: " + error.message);
core.debug("Task definition contents:");
core.debug(JSON.stringify(taskDefContents, undefined, 4));
throw(error);
}
const taskDefArn = registerResponse.taskDefinition.taskDefinitionArn;
core.setOutput('task-definition-arn', taskDefArn);
// Run the task outside of the service
const clusterName = cluster ? cluster : 'default';
const shouldRunTaskInput = core.getInput('run-task', { required: false }) || 'false';
const shouldRunTask = shouldRunTaskInput.toLowerCase() === 'true';
core.debug(`shouldRunTask: ${shouldRunTask}`);
if (shouldRunTask) {
core.debug("Running ad-hoc task...");
await runTask(ecs, clusterName, taskDefArn, waitForMinutes, enableECSManagedTags, waitMaxDelaySeconds);
}
// Update the service with the new task definition
if (service) {
// Determine the deployment controller
const describeResponse = await ecs.describeServices({
services: [service],
cluster: clusterName
});
if (describeResponse.failures && describeResponse.failures.length > 0) {
const failure = describeResponse.failures[0];
throw new Error(`${failure.arn} is ${failure.reason}`);
}
const serviceResponse = describeResponse.services[0];
if (serviceResponse.status != 'ACTIVE') {
throw new Error(`Service is ${serviceResponse.status}`);
}
if (!serviceResponse.deploymentController || !serviceResponse.deploymentController.type || serviceResponse.deploymentController.type === 'ECS') {
// Service uses the 'ECS' deployment controller, so we can call UpdateService
core.debug('Updating service...');
await updateEcsService(ecs, clusterName, service, taskDefArn, waitForService, waitForMinutes, forceNewDeployment, desiredCount, enableECSManagedTags, propagateTags, waitMaxDelaySeconds);
} else if (serviceResponse.deploymentController.type === 'CODE_DEPLOY') {
// Service uses CodeDeploy, so we should start a CodeDeploy deployment
core.debug('Deploying service in the default cluster');
await createCodeDeployDeployment(codedeploy, clusterName, service, taskDefArn, waitForService, waitForMinutes, waitMaxDelaySeconds);
} else {
throw new Error(`Unsupported deployment controller: ${serviceResponse.deploymentController.type}`);
}
} else {
core.debug('Service was not specified, no service updated');
}
}
catch (error) {
core.setFailed(error.message);
core.debug(error.stack);
}
}
module.exports = run;
/* istanbul ignore next */
if (require.main === module) {
run();
}