-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy paths3deploy.js
382 lines (327 loc) · 8.64 KB
/
s3deploy.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
const AWS = require('aws-sdk');
const fs = require('fs');
const { execSync } = require('child_process');
const mime = require('mime-types')
let ID = "";
let SECRET = "";
let BUCKET_NAME = "";
let DEPLOY_FOLDER_PATH = "";
let BUILD_CMD = "";
let CROSS_ACCOUNT_ROLE = "";
let ACL = undefined;
let IGNORE_FILES = [];
let s3;
let sts;
let cloudfront;
let uploadFilesList = [];
const mandatoryOptions = ["ID", "SECRET", "BUCKET_NAME", "DEPLOY_FOLDER_PATH"];
async function init(options)
{
if(s3 && cloudfront)
{
return;
}
if(!checkMandatoryOptions(options))
{
throw new Error(`Mandatory fields missing. Please check if following keys are present -> ${mandatoryOptions}`);
}
ID = options.ID;
SECRET = options.SECRET;
BUCKET_NAME = options.BUCKET_NAME;
DEPLOY_FOLDER_PATH = options.DEPLOY_FOLDER_PATH;
BUILD_CMD = options.BUILD_CMD;
IGNORE_FILES = options.IGNORE_FILES;
CROSS_ACCOUNT_ROLE = options.CROSS_ACCOUNT_ROLE;
if(CROSS_ACCOUNT_ROLE && CROSS_ACCOUNT_ROLE != "")
{
sts = new AWS.STS({
accessKeyId: ID,
secretAccessKey: SECRET
});
const accessparams = await getCrossAccountCredentials();
s3 = new AWS.S3(accessparams);
if(options.CACHE) cloudfront = new AWS.CloudFront(accessparams);
}
else
{
const cred =
{
accessKeyId: ID,
secretAccessKey: SECRET
};
s3 = new AWS.S3(cred);
if(options.CACHE) cloudfront = new AWS.CloudFront(cred);
}
}
function checkMandatoryOptions(options)
{
for(let i in mandatoryOptions)
{
const val = options[mandatoryOptions[i]]
if(!val || val == "" || val == null)
{
return false;
}
}
return true;
}
const getCrossAccountCredentials = async () =>
{
return new Promise((resolve, reject) => {
const timestamp = (new Date()).getTime();
const params = {
RoleArn: CROSS_ACCOUNT_ROLE,
RoleSessionName: `deploy-session-${timestamp}`
};
sts.assumeRole(params, (err, data) => {
if (err) reject(err);
else {
resolve({
accessKeyId: data.Credentials.AccessKeyId,
secretAccessKey: data.Credentials.SecretAccessKey,
sessionToken: data.Credentials.SessionToken,
});
}
});
});
}
function buildProject()
{
if(BUILD_CMD && BUILD_CMD != "")
{
console.log("Build started. CMD : " + BUILD_CMD);
execSync(BUILD_CMD);
console.log('Build Done');
}
else
{
console.log('Skipping build. No command specified.');
}
}
function createBucket()
{
const params = {
Bucket: BUCKET_NAME,
CreateBucketConfiguration: {
// Set your region here
LocationConstraint: "ap-south-1"
}
};
s3.createBucket(params, function(err, data)
{
if (err) console.log(err, err.stack);
else console.log('Bucket Created Successfully', data.Location);
});
}
async function getAllFiles()
{
var params = {
Bucket: BUCKET_NAME
};
return await s3.listObjectsV2(params).promise();
}
async function uploadFile(fileName)
{
// Read content from the file
const fileContent = fs.readFileSync(fileName);
// Setting up S3 upload parameters
const params =
{
Bucket: BUCKET_NAME,
Key: fileName.replace(DEPLOY_FOLDER_PATH, ""),
Body: fileContent,
ContentType: mime.lookup(fileName),
};
if(ACL)
{
params.ACL = ACL;
}
// Uploading files to the bucket
return s3.upload(params).promise();
};
async function deploy(cred)
{
try
{
await init(cred)
buildProject();
prepareDeployParams();
try
{
console.log("File deletion started.");
const deployedFiles = await getAllFiles();
await deleteFiles(deployedFiles);
console.log("All files deleted.");
}
catch(e)
{
console.error("Issue with code deletion.");
}
try
{
console.log("File upload started");
await uploadDeployFiles();
console.log("File upload done successfully");
}
catch(e)
{
console.error("Issue with file upload. ", e.message);
}
try
{
await clearCache(cred);
}
catch(e)
{
console.error("Issue with clearing cache. ", e.message);
}
}
catch(e)
{
console.error(e);
}
}
async function uploadDeployFiles()
{
for(const name of uploadFilesList)
{
console.log(`Uploading file : ${name}`);
await uploadFile(name);
}
}
async function deleteFiles(filesList)
{
if(filesList.length == 0)
{
return;
}
const deleteParams = {
Bucket: BUCKET_NAME,
Delete: { Objects: [] }
};
filesList.Contents.forEach(({ Key }) => {
deleteParams.Delete.Objects.push({ Key });
});
await s3.deleteObjects(deleteParams).promise();
}
function prepareDeployParams()
{
console.log("Preparing deploy files list");
uploadFilesList = [];
readFiles(DEPLOY_FOLDER_PATH, (name) =>
{
uploadFilesList.push(name);
});
console.log("Deploy files list created");
}
function readFiles(dirname, onFileContent, onError)
{
const filenames = fs.readdirSync(dirname);
filenames.forEach(function(filename)
{
if(IGNORE_FILES.includes(filename))
{
return;
}
if(fs.lstatSync(`${dirname}/${filename}`).isDirectory())
{
readFiles(`${dirname}${filename}/`, onFileContent, onError)
}
else
{
onFileContent(`${dirname}${filename}`);
}
});
}
async function clearCache(options)
{
if(options.CACHE)
{
await init(options);
await clearCloudfrontCache(options.CACHE.ID, options.CACHE.PATHS, options.CACHE.QUANTITY)
}
else
{
console.log("Skipping clearing cache. Cache details not provided.");
}
}
async function clearCloudfrontCache(distribution_id, paths, quantity)
{
return new Promise((resolve, reject) =>
{
console.log(`Clearing Cloudfront invalidation for ${distribution_id}`);
var currentTimeStamp = new Date().getTime();
var params =
{
DistributionId: distribution_id,
InvalidationBatch:
{
CallerReference: currentTimeStamp.toString(),
Paths:
{
Quantity : quantity,
Items: paths
}
}
};
cloudfront.createInvalidation(params, function(err, data)
{
if (err)
{
console.log("Error came while cloudfront cache removal",err);
reject(err);
}
else
{
console.log("Cloudfront created invalidation.");
console.log(`Invalidation id : ${data.Invalidation.Id}`);
console.log(`Invalidation status : ${data.Invalidation.Status}`);
resolve(data.Invalidation);
}
});
});
}
/*const data =
{
Location: 'xxxx',
Invalidation:
{
Id: 'xxxx',
Status: 'InProgress',
CreateTime: 2021-11-18T04:04:49.184Z,
InvalidationBatch: { Paths: [Object], CallerReference: '1637208287439' }
}
}
* The identifier for the invalidation request. For example: IDFDVBD632BHDS5.
Id: string;
* The status of the invalidation request. When the invalidation batch is finished, the status is Completed.
Status: string;
* The date and time the invalidation request was first made.
CreateTime: timestamp;
* The current invalidation information for the batch request.
InvalidationBatch: InvalidationBatch;
*/
function getInvalidationStatus(distributionId, invalidationId)
{
const params =
{
'DistributionId' : distributionId,
'Id' : invalidationId
}
cloudfront.getInvalidation(params, (err, data) =>
{
if(err)
{
console.error(`Distribution : ${distributionId} > Invalidation : ${invalidationId}. Error while getting status.`,err);
}
else
{
console.log(`Distribution : ${distributionId} > Invalidation : ${invalidationId} - ${data.Invalidation.Status}`);
}
});
}
module.exports =
{
deploy : deploy,
clearCache : clearCache
}