Purge Cloudflare CDN cache with GitLab CI
I use Cloudflare with this site with custom Page Rule to cache everything.
This means that with each site update I have to flush the CDN cache to propagate changes - we can automate this step.
Last year Cloudflare announced general availability for API Tokens and now we can give more granular permissions, following the principle of least privilege. Avoid using the global API key!
Here the steps:
- Create the API token in the panel. The new token has only cache purge access and only to one site:
- Add masked variables to GitLab CI\CD settings:
- Add an extra stage to
.gitlab-ci.yml
(see more here).
Important: API Tokens use the standard Authorization: Bearer header for authentication instead of x-auth-email
and x-auth-key
that API Keys use.
Important: GitLab CI doesn’t follow the order of stages and execute pages
stage at the end of the pipeline (see open issue). In our case, this is not an issue as purge cache call executes within ~10-15 seconds after the pipeline is complete.
image: monachus/hugo
stages:
- build
- htmltest
- pages
- flushcache
...
flushcache:
image: docker:stable
stage: flushcache
before_script:
- apk add --update curl && rm -rf /var/cache/apk/*
script:
- |
curl --fail --output "/dev/null" --silent --show-error -X POST "https://api.cloudflare.com/client/v4/zones/$CF_ZONE_ID/purge_cache" \
-H "Authorization: Bearer $CF_API_TOKEN" -H "Content-Type: application/json" \
--data '{"purge_everything":true}'