-
Notifications
You must be signed in to change notification settings - Fork 29
/
deploy.js
102 lines (91 loc) · 2.75 KB
/
deploy.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
if (!process.env["CLOUDFRONT_DISTRIBUTION_ID"]) {
throw new Error("CLOUDFRONT_DISTRIBUTION_ID env var must be set");
}
CLOUDFRONT_DISTRIBUTION_ID = process.env["CLOUDFRONT_DISTRIBUTION_ID"];
const lambdaMappings = [
{
FunctionName: "Lambda-Edge-Prerendercloud-dev-viewerRequest",
EventType: "viewer-request"
},
{
FunctionName: "Lambda-Edge-Prerendercloud-dev-originRequest",
EventType: "origin-request"
},
{
FunctionName: "Lambda-Edge-Prerendercloud-dev-originResponse",
EventType: "origin-response"
}
];
const AWS = require("aws-sdk");
AWS.config.region = "us-east-1";
const lambda = new AWS.Lambda();
const cloudfront = new AWS.CloudFront();
const getLastPageOfVersions = (lambdaMapping, Marker) =>
lambda
.listVersionsByFunction({
FunctionName: lambdaMapping.FunctionName,
MaxItems: 1000, // there's a bug that causes this to return 50 no matter what https://github.com/aws/aws-sdk-js/issues/1118
Marker
})
.promise()
.then(res => {
if (res.NextMarker)
return getLastPageOfVersions(lambdaMapping, res.NextMarker);
return res;
});
const getLatestVersion = lambdaMapping =>
getLastPageOfVersions(lambdaMapping)
.then(
res =>
res.Versions.reduce((prev, curr) => (
isNaN(curr.Version)
|| parseInt(prev.Version) > parseInt(curr.Version) ? prev : curr
))
)
.then(latest => ({
EventType: lambdaMapping.EventType,
LambdaFunctionARN: latest.FunctionArn
}));
const updateCloudFront = (cloudFrontId, lambdaMappings) =>
cloudfront.getDistributionConfig({ Id: cloudFrontId }).promise().then(res => {
console.log(
"before",
res.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations
.Items
);
res.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations = {
Quantity: lambdaMappings.length,
Items: lambdaMappings
};
console.log(
"after",
res.DistributionConfig.DefaultCacheBehavior.LambdaFunctionAssociations
.Items
);
const IfMatch = res.ETag;
delete res.ETag;
const Id = cloudFrontId;
return cloudfront
.updateDistribution(Object.assign(res, { Id, IfMatch }))
.promise();
});
return Promise.all(
lambdaMappings.map(lambdaMapping => getLatestVersion(lambdaMapping))
)
.then(lambdaMappings =>
updateCloudFront(CLOUDFRONT_DISTRIBUTION_ID, lambdaMappings)
)
.catch(err => {
console.log(
"\n\n------Error while associating Lambda functions with CloudFront------\n\n"
);
console.error(err);
console.log("\n\n");
})
.then(res => {
console.log("\n\n");
// console.log(res);
console.log(
"\n\nSuccessfully associated Lambda functions with CloudFront\n\n"
);
});