sanlive

Publish static site to Cloudflare Pages and purge previous deployments

This is a really simple shellscript to push pre-built static site files to Cloudflare, then purge previous deployments. It assumes you already know where to find your Cloudflare project name, account ID, and API token, and that you have the Wrangler CLI tool installed.

Please don’t ask me where to get that info. By the time you stumble upon this page, I’ll have already forgotten, and you’ll get answers faster from the Cloudflare docs or other people’s tutorials 🙃 But you will need the following API token settings for this to work:

API token required permissions:

  • Account > Cloudflare Pages > Edit
  • Account > Cloudflare Pages > Read
  • Zone > Cache Purge > Purge

Zone resources settings:

  • Include > All zones from an account > (account)

You should only need to edit the stuff under # set variables. Substitute pathofolderofstaticfiles, yourprojectname, youraccountid, yourapitoken with the correct details and away you go.

#!/bin/zsh

# set variables
DEPLOY_FOLDER=pathtofolderofstaticfiles;
CLOUDFLARE_PROJECT_NAME=yourprojectname;
CLOUDFLARE_ACCOUNT=youraccountid;
CLOUDFLARE_TOKEN=yourapitoken;

# deploy updated site folder to project
CLOUDFLARE_ACCOUNT_ID=$CLOUDFLARE_ACCOUNT \
CLOUDFLARE_API_TOKEN=$CLOUDFLARE_TOKEN \
npx wrangler pages deploy $DEPLOY_FOLDER --project-name $CLOUDFLARE_PROJECT_NAME;

# purge old deployments saved on server
old_deps=($(curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT/pages/projects/$CLOUDFLARE_PROJECT_NAME/deployments \
    -H "Authorization: Bearer $CLOUDFLARE_TOKEN" | jq -r '.result[].id'));
for (( i = 1; i <= ${#old_deps}; i++ )); do
	print "Attempting to delete" $old_deps[$i] $i;
	curl https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT/pages/projects/$CLOUDFLARE_PROJECT_NAME/deployments/$old_deps[$i] \
    -X DELETE \
    -H "Authorization: Bearer $CLOUDFLARE_TOKEN";
done	

exit;

The script uses the wrangler pages deploy call to upload your static files to the server, where they get deployed to your site. Cloudflare automatically saves a history of your deployments, which is useful for people who want history/rollback/etc, but cumbersome for folks with small sites who don’t need it.

After deploying, the script uses curl to access the Cloudflare API endpoint that returns a list of deployments, and saves the deployment IDs from the JSON output to an array.

Then for each deployment ID, it uses curl again to access the Cloudflare API endpoint that deletes the old deployment. Cloudflare has safeguards in place that prevent you from deleting the current deployment in use, but this will purge any unused ones just hanging around.

I felt mighty clever after writing this, because I learned how to use jq and zsh arrays. I also used these very helpful blog posts as references: