I use Cloudflare Pages to serve my blog. Each Git push triggers a new build, resulting in a new deployment on the “Compute (Workers)” page. Over time, I accumulated hundreds of these deployments. I wanted to clean them up, but was surprised to find there’s no automated option for this. As a service provider, Cloudflare should minimize waste and remove unnecessary deployments, but currently, they do not1. There are many forum posts about this, but no official solution. The only useful link points to the API for Pages2.
I already use a custom curl
call to purge caches after each deployment, so I wondered: how hard would it be to automate deployment cleanup myself?
It turned out to be quite straightforward. Within a few minutes, I had a working script. A bit more effort, and I added pagination support.
This script iterates over all deployments, starting from the oldest, and deletes those older than 30 days.
# install prerequisites
sudo apt-get update && sudo apt-get install -y jq
# provide secrets, I use Github Actions hence the syntax
ACCOUNT_ID="${{ secrets.CLOUDFLARE_ACCOUNT_ID }}"
PROJECT_NAME=${{ secrets.CLOUDFLARE_PROJECT_NAME }}"
API_TOKEN="${{ secrets.CLOUDFLARE_PURGE_TOKEN }}"
API_URL="https://api.cloudflare.com/client/v4/accounts/$ACCOUNT_ID/pages/projects/$PROJECT_NAME/deployments"
# for me 30 days is enough
cutoff=$(date -u -d '30 days ago' +"%Y-%m-%dT%H:%M:%SZ")
per_page=25
response=$(curl -s -H "Authorization: Bearer $API_TOKEN" "$API_URL?page=1&per_page=$per_page")
total_pages=$(echo "$response" | jq '.result_info.total_pages')
echo "Total pages: $total_pages"
page=$total_pages
while [ $page -ge 1 ]; do
echo "Processing page: $page"
response=$(curl -s -H "Authorization: Bearer $API_TOKEN" "$API_URL?page=$page&per_page=$per_page")
echo "$response" | jq -c '.result[] | {id: .id, created_on: .created_on}' | while read -r dep; do
dep_id=$(echo "$dep" | jq -r '.id')
dep_date=$(echo "$dep" | jq -r '.created_on')
if [[ "$dep_date" < "$cutoff" ]]; then
echo "Deleting deployment $dep_id from $dep_date"
curl -s -X DELETE -H "Authorization: Bearer $API_TOKEN" "$API_URL/$dep_id"
fi
done
page=$((page-1))
done
To make this work, you need to set up a few things:
- Create an API Token .
- Assign the required permissions3:
- Find your account ID .
- If you use GitHub Actions for builds, create these three secrets in your project:
CLOUDFLARE_ACCOUNT_ID
CLOUDFLARE_PROJECT_NAME
CLOUDFLARE_PURGE_TOKEN
- Run the script (in my case, from
.github/workflows/build.yml
).
That’s it. Enjoy!