13

I have an AngularJS app deployed in S3 & CloudFront. My build process via Grunt & Jenkins includes a FileRev step to uniquely name each new version of my script & vendor JS files. Lastly, FileRev also updates my 'index.html' page tags to refer to the newest versioned editions of my script & vendor files.

All very good, except...

How do I get CloudFront to immediately invalidate 'index.html' in all my edge locations, short of programmatically creating a new invalidation on each release??

Thanks!

EarlD
  • 285
  • 1
  • 3
  • 10
  • You can have index.html versioned as well for each release if you don't want to invalidate. In such cases on each release your loadbalancer or proxy would need to point to new index.html I would just call invalidate on index.html have update the versions of all other ui resources, rather than doing all this circus. – Dhananjay Jul 23 '15 at 20:19
  • 1
    You could configure Jenkins to use the AWS CLI to make a call to invalidate the index.html file in CloudFront https://docs.aws.amazon.com/cli/latest/reference/cloudfront/create-invalidation.html – JaredHatfield Jul 25 '15 at 01:40
  • @EarlD how did you solve it? – carpamon Oct 02 '16 at 04:11
  • I didn't solve it. I simply used the AWS CLI to create an invalidation after every successful build of my application to production. – EarlD Mar 14 '17 at 22:02
  • have a look at my [answer here](http://stackoverflow.com/a/43725605/894273) – Dmitry Efimenko May 01 '17 at 19:58

1 Answers1

4

Here is how you can do this programmatically. This should be a part of your deploy script. We will only invalidate index.html since we are already versioning the other resources via their filenames:

const aws = require('aws-sdk')

function invalidateIndex () {
  const client = new aws.CloudFront({
    accessKeyId: process.env.AWS_ACCESS_ID,
    secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
  })
  const invalidation = client.createInvalidation({
    DistributionId: process.env.AWS_CLOUDFRONT_DISTRIBUTION_ID, /* required */
    InvalidationBatch: {
      /* required */
      CallerReference: Date.now() + '', /* required - request ID given by you, any string is okay*/
      Paths: {
        /* required */
        Quantity: 1, /* required */
        Items: [
          '/',
          /* more items */
        ]
      }
    }
  }, function (err, data) {
    if (err) console.log(err, err.stack); // an error occurred
    else     console.log('Index was invalidated with invalidation id: ', data.Invalidation.Id);           // successful response
  })
}

invalidateIndex()

You can read more in the API documentation here: http://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/CloudFront.html#createInvalidation-property

amit
  • 1,991
  • 1
  • 18
  • 29