forked from smitp/amazon-ecs-run-task
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
283 lines (235 loc) · 8.45 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
const path = require('path')
const core = require('@actions/core')
const aws = require('aws-sdk')
const yaml = require('yaml')
const fs = require('fs')
// 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'
]
const WAIT_DEFAULT_DELAY_SEC = 5
const MAX_WAIT_MINUTES = 360
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 parseCommandString(commandString) {
return commandString.split(' ')
}
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
}
async function run() {
try {
const agent = 'amazon-ecs-run-task-for-github-actions'
const ecs = new aws.ECS({
customUserAgent: agent
})
// Get inputs
const taskDefinitionFile = core.getInput('task-definition', { required: false })
const runLikeService = core.getInput('run-like-service', { required: false })
const clusterName = core.getInput('cluster', { required: false }) || 'default'
const commandOverride = core.getInput('command-override', { required: false })
const count = core.getInput('count', { required: true })
const startedBy = core.getInput('started-by', { required: false }) || agent
const waitForFinish = core.getInput('wait-for-finish', { required: false }) || false
const subnets = core.getInput('subnets', { required: false })
const securityGroups = core.getInput('security-groups', { required: false })
let containerName = core.getInput('container-name', { required: false }) || undefined
let waitForMinutes = parseInt(core.getInput('wait-for-minutes', { required: false })) || 30
if (waitForMinutes > MAX_WAIT_MINUTES) {
waitForMinutes = MAX_WAIT_MINUTES
}
let taskDefArn
let taskSubnets
let taskSecurityGroups
if(!taskDefinitionFile && !runLikeService) {
core.setFailed('Either task-defintion or run-like-service is required. ')
}
if(runLikeService) {
core.debug('Running this like a service')
const getServiceResponse = await ecs.describeServices({
cluster: clusterName,
services: [runLikeService]
}).promise()
core.debug(`Describe service response ${JSON.stringify(getServiceResponse)}`)
const service = getServiceResponse.services[0]
taskDefArn = service.taskDefinition
taskSubnets = service.networkConfiguration.awsvpcConfiguration.subnets
taskSecurityGroups = service.networkConfiguration.awsvpcConfiguration.securityGroups
}
else if(taskDefinitionFile) {
core.debug('Running this with a task definition')
if(!subnets || !securityGroups) {
core.setFailed('Must provide subnets and security-groups unless using run-like-service.')
}
taskSubnets = subnets.split(',')
taskSecurityGroups = securityGroups.split(',')
// 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)))
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)
}
core.debug(`Running task with ${JSON.stringify({
cluster: clusterName,
taskDefinition: taskDefArn,
count: count,
startedBy: startedBy
})}`)
const runTaskResponse = await ecs.runTask({
cluster: clusterName,
taskDefinition: taskDefArn,
launchType: 'FARGATE',
networkConfiguration: {
awsvpcConfiguration: {
assignPublicIp: 'ENABLED',
subnets: taskSubnets,
securityGroups: taskSecurityGroups
},
},
count: count,
startedBy: startedBy,
...(commandOverride && {
overrides: {
containerOverrides: [{
command: parseCommandString(commandOverride),
name: containerName
}]
}}),
}).promise()
core.debug(`Run task response ${JSON.stringify(runTaskResponse)}`)
if (runTaskResponse.failures && runTaskResponse.failures.length > 0) {
const failure = runTaskResponse.failures[0]
throw new Error(`${failure.arn} is ${failure.reason}`)
}
const taskArns = runTaskResponse.tasks.map(task => task.taskArn)
core.setOutput('task-arn', taskArns)
if (waitForFinish && waitForFinish.toLowerCase() === 'true') {
await waitForTasksStopped(ecs, clusterName, taskArns, waitForMinutes)
await tasksExitCode(ecs, clusterName, taskArns)
}
} catch (error) {
core.setFailed(error.message)
core.debug(error.stack)
}
}
async function waitForTasksStopped(ecs, clusterName, taskArns, waitForMinutes) {
if (waitForMinutes > MAX_WAIT_MINUTES) {
waitForMinutes = MAX_WAIT_MINUTES
}
const maxAttempts = (waitForMinutes * 60) / WAIT_DEFAULT_DELAY_SEC
core.debug('Waiting for tasks to stop')
let waitForTries = 0
while (waitForTries < 5) {
try {
waitForTries++;
const waitTaskResponse = await ecs.waitFor('tasksStopped', {
cluster: clusterName,
tasks: taskArns,
$waiter: {
delay: WAIT_DEFAULT_DELAY_SEC,
maxAttempts: maxAttempts
}
}).promise()
core.debug(`Run task response ${JSON.stringify(waitTaskResponse)}`)
break
} catch (e) {
if (waitForTries == 3) {
throw e;
} else {
core.debug('Error trying to wait for task: ' + e.message);
}
}
}
core.info(`All tasks have stopped. Watch progress in the Amazon ECS console: https://console.aws.amazon.com/ecs/home?region=${aws.config.region}#/clusters/${clusterName}/tasks`)
}
async function tasksExitCode(ecs, clusterName, taskArns) {
const describeResponse = await ecs.describeTasks({
cluster: clusterName,
tasks: taskArns
}).promise()
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) {
core.setFailed(failures.join('\n'))
} else {
core.info(`All tasks have exited successfully.`)
}
}
module.exports = run
/* istanbul ignore next */
if (require.main === module) {
run()
}