forked from aws-actions/amazon-ecs-deploy-task-definition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
352 lines (299 loc) · 12.7 KB
/
index.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
const path = require('path');
const core = require('@actions/core');
const aws = require('aws-sdk');
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'
];
// Deploy to a service that uses the 'ECS' deployment controller
async function updateEcsService(ecs, clusterName, service, taskDefArn, waitForService, waitForMinutes, forceNewDeployment) {
core.debug('Updating the service');
await ecs.updateService({
cluster: clusterName,
service: service,
taskDefinition: taskDefArn,
forceNewDeployment: forceNewDeployment
}).promise();
const consoleHostname = aws.config.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://${consoleHostname}/ecs/home?region=${aws.config.region}#/clusters/${clusterName}/services/${service}/events`);
// Wait for service stability
if (waitForService && waitForService.toLowerCase() === 'true') {
core.debug(`Waiting for the service to become stable. Will wait for ${waitForMinutes} minutes`);
const maxAttempts = (waitForMinutes * 60) / WAIT_DEFAULT_DELAY_SEC;
await ecs.waitFor('servicesStable', {
services: [service],
cluster: clusterName,
$waiter: {
delay: WAIT_DEFAULT_DELAY_SEC,
maxAttempts: maxAttempts
}
}).promise();
} else {
core.debug('Not waiting for the service to become stable');
}
}
// 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}'`);
}
function isEmptyValue(value) {
if (value === null || value === undefined || value === '') {
return true;
}
if (Array.isArray(value)) {
for (var element of value) {
if (!isEmptyValue(element)) {
// 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;
}
function emptyValueReplacer(_, value) {
if (isEmptyValue(value)) {
return undefined;
}
if (Array.isArray(value)) {
return value.filter(e => !isEmptyValue(e));
}
return value;
}
function cleanNullKeys(obj) {
return JSON.parse(JSON.stringify(obj, emptyValueReplacer));
}
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) {
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 deploymentGroupDetails = await codedeploy.getDeploymentGroup({
applicationName: codeDeployApp,
deploymentGroupName: codeDeployGroup
}).promise();
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) {
deploymentParams.description = codeDeployDescription
}
const createDeployResponse = await codedeploy.createDeployment(deploymentParams).promise();
core.setOutput('codedeploy-deployment-id', createDeployResponse.deploymentId);
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=${aws.config.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;
}
const maxAttempts = (totalWaitMin * 60) / WAIT_DEFAULT_DELAY_SEC;
core.debug(`Waiting for the deployment to complete. Will wait for ${totalWaitMin} minutes`);
await codedeploy.waitFor('deploymentSuccessful', {
deploymentId: createDeployResponse.deploymentId,
$waiter: {
delay: WAIT_DEFAULT_DELAY_SEC,
maxAttempts: maxAttempts
}
}).promise();
} else {
core.debug('Not waiting for the deployment to complete');
}
}
async function run() {
try {
const ecs = new aws.ECS({
customUserAgent: 'amazon-ecs-deploy-task-definition-for-github-actions'
});
const codedeploy = new aws.CodeDeploy({
customUserAgent: 'amazon-ecs-deploy-task-definition-for-github-actions'
});
// Get inputs
const taskDefinitionContent = core.getInput('task-definition', { required: true });
const service = core.getInput('service', { required: false });
const cluster = core.getInput('cluster', { required: false });
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 forceNewDeployInput = core.getInput('force-new-deployment', { required: false }) || 'false';
const forceNewDeployment = forceNewDeployInput.toLowerCase() === 'true';
let taskDefArn = null;
// Of taskDefContent starts with arn: then we assume it is a task definition ARN
core.debug('taskDefinitionContent: ${taskDefinitionContent}');
//
//
if (taskDefinitionContent.toLowerCase().includes('arn:aws:')) {
taskDefArn = taskDefinitionContent;
//
// Else we assume it is a task definition file
} else {
const taskDefinitionFile = taskDefinitionContent;
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))));
let registerResponse;
try {
registerResponse = await ecs.registerTaskDefinition(taskDefContents).promise();
} 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);
}
taskDefArn = registerResponse.taskDefinition.taskDefinitionArn;
}
core.setOutput('task-definition-arn', taskDefArn);
// Update the service with the new task definition
if (service) {
const clusterName = cluster ? cluster : 'default';
// Determine the deployment controller
const describeResponse = await ecs.describeServices({
services: [service],
cluster: clusterName
}).promise();
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
await updateEcsService(ecs, clusterName, service, taskDefArn, waitForService, waitForMinutes, forceNewDeployment);
} else if (serviceResponse.deploymentController.type === 'CODE_DEPLOY') {
// Service uses CodeDeploy, so we should start a CodeDeploy deployment
await createCodeDeployDeployment(codedeploy, clusterName, service, taskDefArn, waitForService, waitForMinutes);
} 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();
}