A small sinatra app that invalidates assets in a cloudfront distribution when it receives a webhook ping.
Ruby
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
spec Rename the app to app.rb Mar 13, 2014
Gemfile Add error reporting to the app Mar 13, 2014
Gemfile.lock
Procfile Use puma to serve the app Mar 13, 2014
README.md
app.rb
config.ru
puma.rb

README.md

Cloudfront invalidation webhook

A webhook listener that invalidates assets in a cloudfront distribution after a deployment.

Usually the best way to invalidate assets is to version the filenames so that when a new version of the asset is deployed the app stops referencing the old version and starts requesting the new one through the CDN.

Unfortunately we're in a position where people are (legitimately) hotlinking to a single JS file on our site, so we can't use versioned filenames as there's no way to instruct their sites to request a different file.

One solution would be to setup a static endpoint on our site which redirects the browser to the latest version of the asset on the CDN. While this would result in less CDN invalidations than this project introduces, it forces clients to make 2 HTTP requests for the asset, and it also means we still have our customer's visitors hitting our stack on each request.

We have papertrail setup to ping an instance of this app every time our application is deployed to production (We search for memberful-production heroku/api deploy to find relevant deploys), which then tells the Cloudfront API to invalidate the specific JS file our customers use.

Deployment

This is designed to be deployed on Heroku, and should easily be able to run on 1 dyno.

You'll need to set the following config variables:

heroku config:set \
  AWS_ACCESS_KEY_ID=XXXXXXX \
  AWS_SECRET_ACCESS_KEY=XXXXXXX \
  CLOUDFRONT_DISTRIBUTION_ID=XXXXXX \
  FILES_TO_INVALIDATE=/path/to/file1.js,/path/to/file2.js \
  SECURITY_TOKEN="VeryLongRandomStringThatOnlyYouKnow"

The AWS credentials will need the following permissions:

{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Sid": "Stmt1394723093000",
      "Effect": "Allow",
      "Action": [
        "cloudfront:CreateInvalidation"
      ],
      "Resource": [
        "*"
      ]
    }
  ]
}

Then you can setup a papertrail search to watch for deploys and have it ping http://yourherokuapp.herokuapp.com/invalidate?token=VeryLongRandomStringThatOnlyYouKnow.

If you want error reporting then add the free sentry addon.

Job Done.