Skip to content

Instantly share code, notes, and snippets.

@geerlingguy
Last active November 30, 2022 19:26
Show Gist options
  • Save geerlingguy/0e3423ba23f21d1f184b09cbc8a8391d to your computer and use it in GitHub Desktop.
Save geerlingguy/0e3423ba23f21d1f184b09cbc8a8391d to your computer and use it in GitHub Desktop.
Cache purge script to clear Nginx + Cloudflare cache for a given set of URLs.
---
- hosts: webserver
become: true
gather_facts: false
vars:
# API token should be created with cache_purge permissions.
cloudflare_purge_zone: [zone id from cloudflare]
cloudflare_purge_token: "{{ lookup('env','CLOUDFLARE_PURGE_TOKEN') }}"
cloudflare_purge_body:
files:
- https://www.jeffgeerling.com
- https://www.jeffgeerling.com/blog
- https://www.jeffgeerling.com/blog.xml
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
Copy link
Author

geerlingguy commented Oct 5, 2022

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

And GitHub issue: geerlingguy/jeffgeerling-com#150

To keep the token out of the playbook (since it's a sensitive access token), you can either do an env lookup like I did here, or use Ansible Vault or some other secret management tool.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment