Enabling automated purging of Cloudflare cache via API tokens
TypeScriptTo enable automated purging of the Cloudflare cache, you need to create an API token with the necessary permissions to purge the cache. Then, you can write a script to use this token to perform the purge action when needed. Below, I will provide a Pulumi program that automates the creation of a Cloudflare API token with permissions to purge the cache.
Firstly, you will need the
cloudflare
Pulumi provider to interact with your Cloudflare account. You can find more details in the Pulumi Cloudflare Provider documentation.In this example, the
cloudflare.ApiToken
resource is used, which represents an API token in Cloudflare. When creating an API token, you must define a policy that specifies the permissions of the token. In this case, the policy should allow purging of the Cloudflare cache.Here is a TypeScript Pulumi program that creates the API token:
import * as cloudflare from "@pulumi/cloudflare"; // Create a new Cloudflare API token that can purge the cache. const apiToken = new cloudflare.ApiToken("myApiToken", { name: "cache-purge-token", policies: [ { permissionGroups: [ // The permission group ID for cache purge permissions // This ID corresponds to the Cache Purge permissions group // You may need to adjust this ID based on the actual permission group provided by Cloudflare "c8fed203ed3043cba015a93ad1616f1f", ], resources: { // Replace with the correct zone ID or use "*" for all zones "com.cloudflare.api.account.zone.*": "*", }, effect: "allow", }, ], // Optionally, you can specify conditions such as request IP // condition: { ... } }); // Export the API token ID so that it can be used by external scripts export const apiTokenId = apiToken.id;
Make sure you replace the placeholder zone ID with the actual ID of the zone you want to purge, or use
"*"
to allow purging for all zones that the account has access to.This program will create an API token with permissions to purge the cache. You can then use this token with Cloudflare's API in a script to automate the purging process.
Keep in mind that managing API tokens is a sensitive operation; you should protect and restrict access to the token and ensure it is only used in secure and controlled environments.