|
| 1 | +// Attempt a teardown of all Cloudflare Pages preview deployments for a |
| 2 | +// single branch. Used by the docs review-app stop job (deploy_docs.yml) when a |
| 3 | +// merge request is merged/closed or its environment is auto-stopped. |
| 4 | + |
| 5 | +const token = process.env.CLOUDFLARE_API_TOKEN; |
| 6 | +const account = process.env.CLOUDFLARE_ACCOUNT_ID; |
| 7 | +const project = process.env.CF_PAGES_PROJECT; |
| 8 | +const branch = process.env.CF_PAGES_BRANCH; |
| 9 | + |
| 10 | +for (const [name, value] of Object.entries({ |
| 11 | + CLOUDFLARE_API_TOKEN: token, |
| 12 | + CLOUDFLARE_ACCOUNT_ID: account, |
| 13 | + CF_PAGES_PROJECT: project, |
| 14 | + CF_PAGES_BRANCH: branch, |
| 15 | +})) { |
| 16 | + if (!value) { |
| 17 | + console.error(`Missing required env var: ${name}`); |
| 18 | + process.exit(1); |
| 19 | + } |
| 20 | +} |
| 21 | + |
| 22 | +const base = `https://api.cloudflare.com/client/v4/accounts/${account}/pages/projects/${project}`; |
| 23 | +const headers = { Authorization: `Bearer ${token}` }; |
| 24 | + |
| 25 | +async function cf(path, init) { |
| 26 | + const res = await fetch(`${base}${path}`, { |
| 27 | + ...init, |
| 28 | + headers: { ...headers, ...init?.headers }, |
| 29 | + }); |
| 30 | + const body = await res.json().catch(() => ({})); |
| 31 | + if (!res.ok || body.success === false) { |
| 32 | + throw new Error( |
| 33 | + `Cloudflare API ${res.status}: ${JSON.stringify(body.errors ?? body)}`, |
| 34 | + ); |
| 35 | + } |
| 36 | + return body; |
| 37 | +} |
| 38 | + |
| 39 | +// There may be multiple deployments per branch. Wrangler has no function to delete all |
| 40 | +// deployments, so we delete one-by-one. |
| 41 | + |
| 42 | +// Deployments are paginated; walk pages until we stop getting results. |
| 43 | +async function* deployments() { |
| 44 | + for (let page = 1; ; page++) { |
| 45 | + const { result } = await cf(`/deployments?per_page=25&page=${page}`); |
| 46 | + if (!result || result.length === 0) return; |
| 47 | + yield* result; |
| 48 | + if (result.length < 25) return; |
| 49 | + } |
| 50 | +} |
| 51 | + |
| 52 | +let deleted = 0; |
| 53 | +let failed = 0; |
| 54 | +for await (const d of deployments()) { |
| 55 | + const depBranch = d.deployment_trigger?.metadata?.branch; |
| 56 | + if (depBranch !== branch) continue; |
| 57 | + try { |
| 58 | + // force=true also removes deployments that are currently "live" for an alias. |
| 59 | + await cf(`/deployments/${d.id}?force=true`, { method: 'DELETE' }); |
| 60 | + deleted++; |
| 61 | + console.log(`Deleted deployment ${d.id} (branch ${branch})`); |
| 62 | + } catch (err) { |
| 63 | + failed++; |
| 64 | + console.error(`Failed to delete deployment ${d.id}: ${err.message}`); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +console.log(`Done: ${deleted} deleted, ${failed} failed for branch ${branch}.`); |
| 69 | +process.exit(0); |
0 commit comments