geerlingguy / jeffgeerling-com

Drupal Codebase for JeffGeerling.com
https://www.jeffgeerling.com
GNU General Public License v2.0
41 stars 2 forks source link

Nginx + Cloudflare Purge play for Ansible #150

Closed geerlingguy closed 1 year ago

geerlingguy commented 1 year ago

I would like to be able to run a quick Ansible play that both purges the proxy cache in Nginx, and purges relevant URLs in Cloudflare.

Right now I do that manually when I want to make sure a new article or changes post quickly to end users (otherwise it can be anywhere from 10-30 minutes before changes on the site are reflected in the real world).

The playbook should:

  1. Empty the contents of /var/cache/nginx
  2. Restart nginx
  3. Use Cloudflare's API to purge a list of URLs including:
geerlingguy commented 1 year ago

Well this shouldn't be too hard, actually...

---
- hosts: mm
  become: true
  gather_facts: false

  vars:
    # API token should be created with cache_purge permissions.
    cloudflare_purge_zone: [get from cloudflare dashboard]
    cloudflare_purge_token: [create an API token with cache_purge permissions]
    cloudflare_purge_body:
      files:
        - https://www.jeffgeerling.com
        - https://www.jeffgeerling.com/blog
        - https://www.jeffgeerling.com/blog.xml
        - [other files to be purged here]

  tasks:
    - name: Empty out the nginx cache dir.
      shell: rm -f /var/cache/nginx/*

    - name: Restart nginx.
      ansible.builtin.service:
        name: nginx
        state: restarted

    - name: Purge CloudFlare caches
      uri:
        body: '{{ cloudflare_purge_body | to_json }}'
        url: "https://api.cloudflare.com/client/v4/zones/{{ cloudflare_purge_zone }}/purge_cache"
        method: DELETE
        body_format: json
        headers:
          Content-Type: "application/json"
          Authorization: "Bearer {{ cloudflare_purge_token }}"
geerlingguy commented 1 year ago

I created an API token with the Zone.Cache Purge permission in Cloudflare:

Screen Shot 2022-10-05 at 12 31 19 PM

You have to set an API start and end date, so I set mine to be valid until the end of the year. I'll have to update the token next year.

I got the API Zone ID from Cloudflare's UI. I logged in, went to Websites, clicked on my jeffgeerling.com website, then copied out the Zone ID from the right hand column:

Screen Shot 2022-10-05 at 12 33 09 PM

(It's greyed out here, for obvious reasons.)

geerlingguy commented 1 year ago

Blog post: https://www.jeffgeerling.com/blog/2022/clearing-cloudflare-and-nginx-caches-ansible

GitHub Gist: https://gist.github.com/geerlingguy/0e3423ba23f21d1f184b09cbc8a8391d