Last active
March 4, 2019 00:58
-
-
Save litwicki/d24c612410124bebb0d8e771c09be63e to your computer and use it in GitHub Desktop.
A lambda intended to be triggered on a PUT from a CodeDeploy build and then unzip and deploy to a separate bucket.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var deployBucket = 'example.com'; | |
var region = 'us-west-2'; | |
// If you're hosting a static html (or javascript) website | |
// the domain and bucket you host from (deploy to) should be | |
// identical, but feel free to change based on your circumstances. | |
var domain = deployBucket; | |
var aws = require('aws-sdk'); | |
var ep = new aws.Endpoint('s3.' + region + '.amazonaws.com'); | |
var s3 = new aws.S3({endpoint: ep}); | |
var mime = require('mime-types'); | |
var async = require('async'); | |
var JSZip = require('jszip'); | |
exports.handler = function(event, context, callback) { | |
console.log('Node:' + JSON.stringify(process.versions)); | |
console.log('Received event:', JSON.stringify(event, null, 2)); | |
// Get the object from the event and show its content type | |
var bucket = event.Records[0].s3.bucket.name; | |
var key = event.Records[0].s3.object.key; | |
s3.getObject({Bucket:bucket, Key:key}, | |
function(err,data) { | |
if (err) { | |
console.log('Error getting object ' + key + ' from bucket ' + bucket + '. Make sure they exist and your bucket is in the same region as this function.'); | |
context.fail('Error', 'Error getting file: ' + err); | |
return; | |
} | |
if (data.ContentType != 'application/zip') { | |
console.log('not zip!:' + data.ContentType); | |
context.succeed(); | |
return; | |
} | |
var zip = new JSZip(data.Body); | |
async.forEach(zip.files, function (zippedFile) { | |
var f = zippedFile; | |
var mimetype = mime.lookup(f.name); | |
if (mimetype == false) { | |
mimetype = 'application/octet-stream'; | |
} | |
var fbuffer = new Buffer(f.asBinary(), 'binary'); | |
//verify all javascript files and change domain | |
if(mimetype === 'application/javascript') { | |
fbuffer = Buffer.concat([fbuffer, new Buffer('\ndocument.domain = \'' + domain + '\';')]); | |
} | |
s3.putObject({ | |
Bucket: deployBucket, | |
Key: f.name, | |
Body: fbuffer, | |
ContentType: mimetype, | |
CacheControl: 'no-cache', | |
Expires: 0 | |
}, function(err, data) { | |
if (err) { | |
context.fail(err, 'unzip error'); | |
} | |
console.log('success to unzip:' + f.name); | |
} | |
); | |
}, function (err) { | |
if (err) { | |
context.fail(err, 'async forEach error'); | |
} | |
console.log('all finish!'); | |
context.succeed(); | |
}); | |
}); | |
callback(null, "Build deployed successfully!"); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment