forked from aws-actions/amazon-ecs-deploy-task-definition
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
240 lines (205 loc) · 8.78 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
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 CODE_DEPLOY_WAIT_BUFFER_MINUTES = 10;
const CODE_DEPLOY_MAX_WAIT_MINUTES = 360; // 6 hours
const CODE_DEPLOY_MIN_WAIT_MINUTES = 30;
const CODE_DEPLOY_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'
];
// Deploy to a service that uses the 'ECS' deployment controller
async function updateEcsService(ecs, clusterName, service, taskDefArn, waitForService) {
core.debug('Updating the service');
await ecs.updateService({
cluster: clusterName,
service: service,
taskDefinition: taskDefArn
}).promise();
// Wait for service stability
if (waitForService && waitForService.toLowerCase() === 'true') {
core.debug('Waiting for the service to become stable');
await ecs.waitFor('servicesStable', {
services: [service],
cluster: clusterName
}).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 undefinedOrNullReplacer(_, value) {
if (value === null || value === undefined) {
return undefined;
}
return value;
}
function cleanNullKeys(obj) {
return JSON.parse(JSON.stringify(obj, undefinedOrNullReplacer));
}
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;
}
// Deploy to a service that uses the 'CODE_DEPLOY' deployment controller
async function createCodeDeployDeployment(codedeploy, clusterName, service, taskDefArn, waitForService) {
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 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');
const createDeployResponse = await codedeploy.createDeployment({
applicationName: codeDeployApp,
deploymentGroupName: codeDeployGroup,
revision: {
revisionType: 'AppSpecContent',
appSpecContent: {
content: appSpecString,
sha256: appSpecHash
}
}
}).promise();
core.setOutput('codedeploy-deployment-id', createDeployResponse.deploymentId);
// 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 + CODE_DEPLOY_WAIT_BUFFER_MINUTES;
if (totalWaitMin > CODE_DEPLOY_MAX_WAIT_MINUTES) {
totalWaitMin = CODE_DEPLOY_MAX_WAIT_MINUTES;
}
if (totalWaitMin < CODE_DEPLOY_MIN_WAIT_MINUTES) {
totalWaitMin = CODE_DEPLOY_MIN_WAIT_MINUTES;
}
const maxAttempts = (totalWaitMin * 60) / CODE_DEPLOY_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: CODE_DEPLOY_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 taskDefinitionFile = 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 });
// 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 = removeIgnoredAttributes(cleanNullKeys(yaml.parse(fileContents)));
const registerResponse = await ecs.registerTaskDefinition(taskDefContents).promise();
const taskDefArn = registerResponse.taskDefinition.taskDefinitionArn;
core.setOutput('task-definition-arn', taskDefArn);
// Update the service with the new task definition
if (service) {
const clusterName = cluster
// 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) {
// Service uses the 'ECS' deployment controller, so we can call UpdateService
await updateEcsService(ecs, clusterName, service, taskDefArn, waitForService);
} else if (serviceResponse.deploymentController.type == 'CODE_DEPLOY') {
// Service uses CodeDeploy, so we should start a CodeDeploy deployment
await createCodeDeployDeployment(codedeploy, clusterName, service, taskDefArn, waitForService);
} 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();
}