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:

  1. Create the API token in the panel. The new token has only cache purge access and only to one site:
create the API token in Cloudflare panel
  1. Add masked variables to GitLab CI\CD settings:
add variables to GitLab CI\CD settings
  1. 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

    - build
    - htmltest
    - pages
    - flushcache


    image: docker:stable
    stage: flushcache
        - apk add --update curl && rm -rf /var/cache/apk/*
    - |
        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}'