Clear Your CloudFlare Cache When You Deploy to Openshift

Make sure CloudFlare has the latest site data when you update.

0 Comments

Love Openshift and CloudFlare, well make that relationship even better with a bit of automation. CloudFlare is a great Content Distribution Network (CDN) that allows you to run your website on smaller servers, while not compromising responsiveness. If you are not familiar with them then please take a moment to check them out, it could be just the boost you’re looking for. For those savvy with CloudFlare, one really cool feature is the ability to cache static HTML pages; if you recall from a previous post, my site is now entirely static. This means clearing your cache is a must when you want changes to show up to your viewers as quickly as possible.

Caching HTML?

Commenter (John B. Roberts) was kind enought to suggest that I mention HTML is not cached by default. In order to set this up please see CloudFlare’s support page on the topic “How do I cache static HTML?” Once you get this setup you are on your way to excellent load times and a low server load.

The Problem

Currently there are only two ways to clear the CloudFlare cache, via the site or their API. Most users will opt to use the website to clear the cache and this means after every update you must login to CloudFlare and click the “purge cache” button. While this is not particularly difficult, it is rather annoying.

API Shall We?

CloudFlare’s API comes to the rescue to allow us to automate this process. If you utilize OpenShift to host your site, you can use the git hooks to utilize the CloudFlare API. The hook we are interested in is the post_deploy hook, it will allow us to clear the cache after the site has been uploaded and deployed.

Let’s Create That Hook

Credentials

In order to utilize the CloudFlare API you will need to gather a few bits of CloudFlare data.

Create The File

Now that you have your credentials you will need to create the actual hook. You can find this in your checked out repo .openshift/action_hooks/post_deploy . Copy the script below, or use the download button to download it, and place it in the file mentioned. Make sure you change the variables at the top to match the credentials you gathered.

email=your@email.com
tkn=API_TOKEN
domain=yourdomain.com

zone=$(curl -s -X GET "https://api.CloudFlare.com/client/v4/zones?name=${domain}&status=active&page=1&per_page=20&order=status&direction=desc&match=all" \
-H "X-Auth-Email: ${email}" \
-H "X-Auth-Key: ${tkn}" \
-H "Content-Type: application/json")

zone=${zone:18:32}

curl -X DELETE "https://api.CloudFlare.com/client/v4/zones/${zone}/purge_cache" \
-H "X-Auth-Email: ${email}" \
-H "X-Auth-Key: ${tkn}" \
-H "Content-Type: application/json" \
--data '{"purge_everything":true}'

unset zone email tkn domain

Download post_deploy

- By: Last Updated:

Comments

Small ad here
Select a size at which to preview the size