Invalidate an Entire CloudFront Distribution from the Command Line
Whenever I push CSS or layout changes to the blog, I like to invalidate my CloudFront cache to ensure the changes propagate near-synchronously.
For instance during a new UI update, if a CSS file were to take 12 hours to propagate into the caches, but the layout changes only take 4 hours, there would be 8 hours where the new layout isn’t properly styled.
To do this, CloudFront supports invalidations to the cache. You get 1000 free invalidations per year, after which it costs $0.005 per invalidation. That’s not necessarily expensive at all, but rather then blow through the 1000 free invalidations by individually invalidating the files, you can take advantage of the wildcard invalidation that was added in May 2015.
The wildcard invalidation works very similarly to other systems, giving you the ability to use the asterisk operator (*) to specify a file pattern to invalidate. For instance, to invalidate all images you might do something like this:
You can also invalidate your entire cache like so:
For my purposes, I wanted to just invalidate the entire cache to be safe, since almost all pages use the same layout and styling. I also wanted to add this to my deploy script so I wouldn’t have to manually go into the CloudFront management console. Luckily for us, the command line tools offer invalidation support with the create-invalidation command:
aws cloudfront create-invalidation --distribution-id $CLOUDFRONT_ID \ --paths /\*
Simply replace $CLOUDFRONT_ID with your CloudFront distribution ID. The path I’m specifying here is for /*, but you’ll want to update that to match the path for your use case.
The only thing to remember is you must escape the asterisk with a backslash, otherwise you’ll end up with the following error message indicating your path is invalid:
A client error (InvalidArgument) occurred when calling the CreateInvalidation operation: Your request contains one or more invalid invalidation paths.