Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Amazon CloudFront Versioning 'index.html'

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!

like image 390
EarlD Avatar asked Jul 23 '15 15:07

EarlD


People also ask

Can I terminate HTTP to HTTPS using CloudFront?

CloudFront doesn't redirect DELETE , OPTIONS , PATCH , POST , or PUT requests from HTTP to HTTPS. If you configure a cache behavior to redirect to HTTPS, CloudFront responds to HTTP DELETE , OPTIONS , PATCH , POST , or PUT requests for that cache behavior with HTTP status code 403 (Forbidden).

How do I get rid of CloudFront invalidation?

If you need to remove a file from CloudFront edge caches before it expires, you can do one of the following: Invalidate the file from edge caches. The next time a viewer requests the file, CloudFront returns to the origin to fetch the latest version of the file.

What is OAI in CloudFront?

An origin access identity is a special CloudFront user that you can associate with Amazon S3 origins, so that you can secure all or just some of your Amazon S3 content. For more information, see Restricting Access to Amazon S3 Content by Using an Origin Access Identity in the Amazon CloudFront Developer Guide.


1 Answers

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

like image 186
amit Avatar answered Oct 24 '22 08:10

amit