Files
test/.github/workflows/bind-everything.yml

62 lines
2.3 KiB
YAML

name: Sync CF D1 & KV Bindings
on:
push:
branches: ["**"]
workflow_dispatch:
permissions:
contents: write
jobs:
sync:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version: 20
- name: Install Wrangler & jq
run: |
npm i -g wrangler
sudo apt-get update -y && sudo apt-get install -y jq
- name: Fetch Account ID & Sync wrangler.toml
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
run: |
set -u
AID=$(curl -fsSL https://api.cloudflare.com/client/v4/accounts \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
| jq -r '.result[0].id')
[ -n "$AID" ] || { echo "No account id"; exit 1; }
export CLOUDFLARE_ACCOUNT_ID="$AID"
touch wrangler.toml
# D1: append missing bindings
(wrangler d1 list --json 2>/dev/null || echo '[]') \
| jq -c '.[]?' | while read -r db; do
id=$(jq -r '.uuid' <<<"$db"); grep -q "$id" wrangler.toml && continue
name=$(jq -r '.name' <<<"$db")
bind=$(printf "%s" "$name" | tr '[:lower:]' '[:upper:]' | sed -E 's/[^A-Z0-9]+/_/g')
printf '\n[[d1_databases]]\nbinding="%s"\ndatabase_name="%s"\ndatabase_id="%s"\n' "$bind" "$name" "$id" >> wrangler.toml
done
# KV: append missing namespaces
curl -fsSL "https://api.cloudflare.com/client/v4/accounts/$CLOUDFLARE_ACCOUNT_ID/storage/kv/namespaces?per_page=1000" \
-H "Authorization: Bearer $CLOUDFLARE_API_TOKEN" -H "Content-Type: application/json" \
| jq -c '.result[]?' | while read -r ns; do
id=$(jq -r '.id' <<<"$ns"); grep -q "$id" wrangler.toml && continue
title=$(jq -r '.title' <<<"$ns")
bind=$(printf "%s" "$title" | tr '[:lower:]' '[:upper:]' | sed -E 's/[^A-Z0-9]+/_/g')
printf '\n[[kv_namespaces]]\nbinding="%s"\nid="%s"\n' "$bind" "$id" >> wrangler.toml
done
- name: Commit and Push Changes
uses: stefanzweifel/git-auto-commit-action@v5
with:
commit_message: "chore: sync D1 + KV bindings"
file_pattern: wrangler.toml