-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathindex.js
413 lines (356 loc) · 11.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
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
const fs = require('fs')
const AWS = require('aws-sdk')
/**
* Validates a configuration object
* @param {CommandConfig} config A command configuration object
* @param {string[]} requiredFields List of required config fields (excluding cfTriggers)
* @param {string[]} requiredTriggerFields List of required config fields for each trigger
* @returns {boolean}
*/
const validateConfig = (config, requiredFields = [], requiredTriggerFields = []) => {
const validFields = [
'dryRun',
'awsRegion',
's3Region',
'lambdaRegion',
'cfDistributionID',
'cacheBehaviorPath',
'autoIncrementVersion',
'lambdaCodeS3Bucket',
'lambdaCodeS3Bucket',
'cfTriggers',
]
const validTriggerFields = [
'cfTriggerName',
'lambdaFunctionName',
'lambdaFunctionVersion',
'lambdaCodeS3Key',
'lambdaCodeFilePath',
]
// ensure all fields in the config are expected
for (let field of Object.keys(config)) {
if (!validFields.includes(field)) {
console.log(`[VALIDATION ERROR]: unknown field '${field}' found in config.`, config)
return false
}
}
// ensure all required fields are defined
for (let field of requiredFields) {
if (typeof config[field] === 'undefined') {
console.log(`[VALIDATION ERROR]: '${field}' is required for each trigger.`, config)
return false
}
}
// ensure that there is at least one trigger
if (!config.cfTriggers?.length) {
console.log(`[VALIDATION ERROR]: at least one trigger configuration is required.`, config)
return false
}
// validate each trigger configuration
for (let trigger of config.cfTriggers) {
// ensure all fields in the trigger confg are expected
for (let field of Object.keys(trigger)) {
if (!validTriggerFields.includes(field)) {
console.log(`[VALIDATION ERROR]: unknown field '${field}' found in trigger config.`, trigger)
return false
}
}
// ensure all required fields are defined
for (let field of requiredTriggerFields) {
if (typeof trigger[field] === 'undefined') {
console.log(`[VALIDATION ERROR]: '${field}' is required for each trigger.`, trigger)
return false
}
}
}
return true
}
/**
* Iterates through all the versions of a Lambda function to find the most recent sequential version
*
* @param {Lambda.FunctionName} functionName The fully qualified Lambda function name
* @param {AWS.Region} region The AWS region the Lambda is in
* @param {string} version The sequential version number to get (gets the latest if blank)
* @returns {Promise<Lambda.Version>}
*/
const getLambdaVersion = async (functionName, region, version = '') => {
const lambda = new AWS.Lambda({
apiVersion: '2015-03-31',
region,
})
const versions = []
let nextMarker
do {
const versionData = await lambda
.listVersionsByFunction({
FunctionName: functionName,
Marker: nextMarker,
})
.promise()
nextMarker = versionData.NextMarker
versions.push(...versionData.Versions)
} while (nextMarker)
// if no versions have been published, return an empty version
if (!versions.length) {
return {
Version: '0',
}
}
if (version) {
return versions.find((v) => v.Version === version)
}
return versions
.filter((version) => version.Version !== '$LATEST')
.sort((a, b) => Number(b.Version) - Number(a.Version))[0]
}
/**
* Fetches the full configuration for a CloudFront distribution
*
* @param {CloudFront.DistributionId} distributionID The CloudFront distribution ID
* @returns {Promise<CloudFront.DistributionConfig>}
*/
const getCloudFrontDistributionConfig = async (distributionID) => {
const cloudfront = new AWS.CloudFront({
apiVersion: '2020-05-31',
})
return cloudfront
.getDistributionConfig({
Id: distributionID,
})
.promise()
}
/**
* Modifies a CloudFront configuration with a new Lambda ARN for a specific trigger
*
* @param {CloudFront.DistributionConfig} distributionConfig The current CloudFront distribution config
* @param {string} cacheBehaviorPath The PathPattern of the CacheBehavior to update, or "default" to use DefaultCacheBehavior
* @param {Lambda.Arn} lambdaARN The ARN for the new Lambda to use as a trigger
* @param {CloudFront.EventType} triggerName The name of the trigger event ['viewer-request'|'origin-request'|'origin-response'|'viewer-response']
* @returns {*}
*/
const changeCloudFrontDistributionLambdaARN = (distributionConfig, cacheBehaviorPath, lambdaARN, triggerName) => {
try {
const cacheBehavior =
cacheBehaviorPath === 'default'
? distributionConfig.DistributionConfig.DefaultCacheBehavior
: distributionConfig.DistributionConfig.CacheBehaviors.Items.find(
(item) => item.PathPattern === cacheBehaviorPath,
)
if (!cacheBehavior) {
console.log('No cache behavior found for PathPattern', cacheBehaviorPath)
return distributionConfig
}
const lambdaFunction = cacheBehavior.LambdaFunctionAssociations.Items.find((item) => item.EventType === triggerName)
if (lambdaFunction.LambdaFunctionARN !== lambdaARN) {
lambdaFunction.LambdaFunctionARN = lambdaARN
}
} catch (e) {
// do nothing
}
return distributionConfig
}
/**
* Updates a CloudFront distribution with the provided config
*
* @param {CloudFront.DistributionId} distributionID The CloudFront distribution ID
* @param {CloudFront.DistributionConfig} distributionConfig The current CloudFront distribution config
* @returns {Promise<CloudFront.UpdateDistributionResult, AWSError>}
*/
const updateCloudFrontDistribution = async (distributionID, distributionConfig) => {
const cloudfront = new AWS.CloudFront({
apiVersion: '2020-05-31',
})
return cloudfront
.updateDistribution({
Id: distributionID,
IfMatch: distributionConfig.ETag,
DistributionConfig: distributionConfig.DistributionConfig,
})
.promise()
}
/**
* Pushes a ZIP file containing Lambda code to S3
*
* @param config The project configuration to update
*
* @return {Promise<void>}
*/
const pushNewCodeBundles = async (config) => {
if (
!validateConfig(config, ['lambdaCodeS3Bucket'], ['lambdaFunctionName', 'lambdaCodeS3Key', 'lambdaCodeFilePath'])
) {
throw new Error('Invalid config.')
}
const s3 = new AWS.S3({
apiVersion: '2006-03-01',
region: config.s3Region || config.awsRegion,
})
for (let trigger of config.cfTriggers) {
let version = trigger.lambdaFunctionVersion
if (trigger.lambdaFunctionName && config.autoIncrementVersion) {
version = `${
Number((await getLambdaVersion(trigger.lambdaFunctionName, config.lambdaRegion || config.awsRegion)).Version) +
1
}`
}
let key = trigger.lambdaCodeS3Key
if (version) {
key = key.replace(/\.zip$/, `-${version}.zip`)
}
const s3Config = {
Bucket: config.lambdaCodeS3Bucket,
Key: key,
Body: fs.createReadStream(trigger.lambdaCodeFilePath),
}
console.log('Pushing to S3 with the following config:', {
...s3Config,
Body: `File: ${trigger.lambdaCodeFilePath}`,
})
if (config.dryRun) {
console.log('[DRY RUN]: Not pushing code bundles to S3')
continue
}
await s3.upload(s3Config).promise()
console.log('Successfully pushed to S3.')
}
}
/**
* Updates a Lambda function's code with a ZIP file in S3
*
* @param config The project configuration to update
*
* @return {Promise<void>}
*/
const deployLambdas = async (config) => {
if (!validateConfig(config, ['lambdaCodeS3Bucket'], ['lambdaFunctionName', 'lambdaCodeS3Key'])) {
throw new Error('Invalid config.')
}
const lambda = new AWS.Lambda({
apiVersion: '2015-03-31',
region: config.lambdaRegion || config.awsRegion,
})
const s3 = new AWS.S3({
apiVersion: '2006-03-01',
region: config.s3Region || config.awsRegion,
})
for (let trigger of config.cfTriggers) {
let version = trigger.lambdaFunctionVersion
if (config.autoIncrementVersion) {
version = `${
Number((await getLambdaVersion(trigger.lambdaFunctionName, config.lambdaRegion || config.awsRegion)).Version) +
1
}`
}
let key = trigger.lambdaCodeS3Key
if (version) {
key = key.replace(/\.zip$/, `-${version}.zip`)
}
let lambdaConfig
if (config.s3Region && config.lambdaRegion && config.s3Region !== config.lambdaRegion) {
console.log("S3 and Lambda regions don't match. Downloading ZIP from S3...")
lambdaConfig = {
FunctionName: trigger.lambdaFunctionName,
ZipFile: await s3
.getObject({
Bucket: config.s3BucketName,
Key: key,
})
.promise()
.then((data) => data.Body),
}
} else {
console.log('S3 and Lambda regions match.')
lambdaConfig = {
FunctionName: trigger.lambdaFunctionName,
S3Bucket: config.lambdaCodeS3Bucket,
S3Key: key,
}
}
console.log('Updating Lambda code with the following config', lambdaConfig)
if (config.dryRun) {
console.log('[DRY RUN]: Not updating Lambda function code')
continue
}
await lambda.updateFunctionCode(lambdaConfig).promise()
console.log('Successfully deployed new code.')
}
}
/**
* Publishes a new version of a Lambda function
*
* @param config The project configuration to update
*
* @return {Promise<void>}
*/
const publishLambdas = async (config) => {
if (!validateConfig(config, [], ['lambdaFunctionName'])) {
throw new Error('Invalid config.')
}
const lambda = new AWS.Lambda({
apiVersion: '2015-03-31',
region: config.lambdaRegion || config.awsRegion,
})
for (let trigger of config.cfTriggers) {
const lambdaConfig = {
FunctionName: trigger.lambdaFunctionName,
}
console.log('Publishing new Lambda version with the following config:', lambdaConfig)
if (config.dryRun) {
console.log('[DRY RUN]: Not publishing new Lambda versions')
continue
}
await lambda.publishVersion(lambdaConfig).promise()
console.log('Successfully published new Lambda version.')
}
}
/**
* Sets the Lambda@Edge triggers for the specified Lambda functions on the specified CloudFront distribution
*
* @param config The project configuration to update
*
* @return {Promise<void>}
*/
const activateLambdas = async (config) => {
if (!validateConfig(config, ['cfDistributionID', 'cacheBehaviorPath'], ['lambdaFunctionName'])) {
throw new Error('Invalid config.')
}
// first, get the CF distro
const distroConfig = await getCloudFrontDistributionConfig(config.cfDistributionID)
const lambdaARNs = {}
await Promise.all(
config.cfTriggers.map(async (trigger) => {
lambdaARNs[trigger.cfTriggerName] = (
await getLambdaVersion(
trigger.lambdaFunctionName,
config.lambdaRegion || config.awsRegion,
config.autoIncrementVersion ? '' : trigger.lambdaFunctionVersion,
)
).FunctionArn
}),
)
console.log('Activating the following ARNs:', lambdaARNs)
const cacheBehaviorPath = config.cacheBehaviorPath
// then, set the arns in the config (filter out missing arns)
const updatedConfig = Object.entries(lambdaARNs)
.filter(([, arn]) => !!arn)
.reduce(
(config, [triggerName, arn]) =>
changeCloudFrontDistributionLambdaARN(config, cacheBehaviorPath, arn, triggerName),
distroConfig,
)
// do not update if this is a dry run
if (config.dryRun) {
console.log('[DRY RUN]: Not updating CloudFront distribution triggers')
return
}
// finally, update the distro
await updateCloudFrontDistribution(config.cfDistributionID, updatedConfig)
console.log('Successfully activated new Lambdas.')
}
module.exports = {
pushNewCodeBundles,
deployLambdas,
publishLambdas,
activateLambdas,
validateConfig,
}