Posted By

chrisaiv on 03/08/18


Tagged

lambda aws


Versions (?)

AWS Lambda: When data is uploaded to S3 bucket, clear CloudFront cache


 / Published in: JavaScript
 

This is a pretty simple example of how to create a Lambda function that will clear a CloudFront cache connected to an S3 bucket

  1. /**
  2.  * Created by Chris Mendez
  3.  * Last Updated: 03/09/2018
  4.  * Documentation:
  5.  *
  6.  * CloudFront Docs and Examples:
  7.  *
  8.  *
  9.  *
  10.  */
  11.  
  12. 'use strict';
  13. var AWS = require('aws-sdk');
  14. var moment = require('moment-timezone');
  15.  
  16. var cloudfront = new AWS.CloudFront({
  17. region: process.env.CLOUDFRONT_REGION_ID
  18. });
  19.  
  20. exports.handler = function (event, context, callback) {
  21. _log('~~ CLOUDFRONT INVALIDATION ~~', moment().tz('America/Los_Angeles').format('MMMM Do YYYY, h:mm:ss a'));
  22. _log('event: ' + JSON.stringify(event));
  23.  
  24. var bucket = event.Records[0].s3.bucket.name;
  25. var key = event.Records[0].s3.object.key;
  26.  
  27. // Parameters for a invalidation
  28. var params = {
  29. DistributionId: process.env.CLOUDFRONT_DISTRIBUTION_ID,
  30. InvalidationBatch: {
  31. CallerReference: '' + new Date().getTime(),
  32. Paths: {
  33. Quantity: 1,
  34. Items : [ '/' + key ]
  35. }
  36. }
  37. };
  38.  
  39. _log('Params: ', params);
  40. _log('Bucket: ' + bucket);
  41. _log('Key: ' + key);
  42.  
  43. // Invalidate
  44. cloudfront.createInvalidation(params, function (err, data) {
  45. if (err) {
  46. _log('Error: ', err);
  47. return;
  48. }
  49. _log('Success: ', data.InvalidationBatch);
  50. });
  51.  
  52. function _log(caption, object) {
  53. console.log(caption + JSON.stringify(object, true, ' '));
  54. }
  55. }

Report this snippet  

You need to login to post a comment.