Wrangle(r) multiple Cloudflare accounts
· John MassonOver time I've collected a few Cloudflare accounts that separate work, personal and side-projects. I really like using wrangler, the Cloudflare CLI tool, but I'd gotten sick of having to wrangler logout, wrangler login (and click through the browser for OAuth) when I needed to switch between these accounts, to the point where I'd stopped using it out of laziness.
Then I hit this error:
Interestingly that link seems to be a short lived one generated at error time I think? It doesn't work now but at the time it led me here.
You may not be able to delete your Pages project if it has a high number (over 100) of deployments. The Cloudflare team is tracking this issue.
As a workaround, you can use
wrangler pages deployment deleteto delete deployments individually. After you delete your deployments, you will be able to delete your Pages project.
As these things go, I really couldn't bring myself to log out/in again manually for the rest of my life, but it generated the motivation to set up the automated fix.
Cloudflare lets you create scoped API tokens for all sorts of automation tasks. You probably already have a few and you can use one to solve this problem too.
Generate a token scoped to allow the tasks you routinely do from the command line (they have some good templates to start with), save it to the macOS Keychain (so there's no plaintext token sitting in a dotfile) and let direnv load the right one, depending on which project you're working on.
The token goes into the Keychain once:
security add-generic-password -U -s cf-token-personal -a wrangler -w
And then your per-repo setup is a gitignored .envrc with this command, changing cf-token-personal for whatever you name the applicable token for this account:
# loaded automatically on cd
export CLOUDFLARE_API_TOKEN="$(security find-generic-password -s cf-token-personal -a wrangler -w)"
So now when you cd into a project, the CLOUDFLARE_API_TOKEN is set and any run of the wrangler command grabs it from the environment automatically (i.e. no flag to pass, etc), so it always has access to the correct account.
When there's no CLOUDFLARE_API_TOKEN set, it falls back to the global OAuth session, but I preferred to log it out so if I'm somewhere unconfigured it fails with an auth error. That both reminds me to set up the .envrc and prevents it silently doing something to the wrong account.