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!
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).
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With