Last active
July 22, 2017 04:01
-
-
Save mahayash315/38b9938f7058b60d5e7db3fa43aa555b to your computer and use it in GitHub Desktop.
Invalidates objects on CloudFront triggered by S3 event
This file contains 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
/** | |
* Invalidates objects on CloudFront triggered by S3 event | |
* Runtime: Node.js 6.10 | |
*/ | |
var aws = require('aws-sdk'); | |
var cloudfront = new aws.CloudFront(); | |
// returns if the Bucket is used in the Distribution | |
var bucketIsUsed = (distribution, bucketName) => { | |
return distribution.Origins.Items.some(function(origin) { | |
return (origin.DomainName.indexOf(bucketName) === 0); | |
}); | |
}; | |
// creates an invalidation batch and returns Promise | |
var invalidate = (distribution, objectKey) => { | |
return cloudfront.createInvalidation({ | |
DistributionId: distribution.Id, | |
InvalidationBatch: { | |
CallerReference: '' + new Date().getTime(), | |
Paths: { | |
Quantity: 1, | |
Items: [ '/' + objectKey ] | |
} | |
} | |
}).promise(); | |
}; | |
exports.handler = (event, context, callback) => { | |
var bucketName = event.Records[0].s3.bucket.name; | |
var objectKey = event.Records[0].s3.object.key; | |
console.log('Bucket Name: '+bucketName); | |
console.log('Object Key: '+objectKey); | |
const listDistributionsPromise = cloudfront.listDistributions({}).promise(); | |
listDistributionsPromise.then( (data) => { | |
var distributions = data.DistributionList.Items; | |
var usedDistributions = distributions.filter( (distribution) => { | |
// filter distributions by the bucket name | |
return bucketIsUsed(distribution, bucketName) | |
}); | |
return usedDistributions; | |
}).then( (usedDistributions) => { | |
return Promise.all(usedDistributions.map( (usedDistribution) => { | |
// perform invalidation | |
return invalidate(usedDistribution, objectKey); | |
})); | |
}).then( (data) => { | |
// done | |
console.log('done!'); | |
console.log(JSON.stringify(data)); | |
context.done(null, ''); | |
}).catch( (err) => { | |
console.error('Error: ', err); | |
context.done('error', err); | |
}) | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment