pr_01m47d24b0e6n91zwymwxg0vpx/scripts/setup-deployments.sh
| 1 | #!/usr/bin/env bash |
| 2 | # Sets up what Deployments needs on a Cloudflare account, once. Safe to run |
| 3 | # again: each step skips what exists. Then deploy with scripts/deploy.sh. |
| 4 | # |
| 5 | # Needs the Workers for Platforms add-on on the account, and a zone for |
| 6 | # apps (g1t uses g1t.page) named in services/pages/wrangler.jsonc. |
| 7 | # |
| 8 | # Two steps need more than `wrangler login` can do: a wildcard DNS record |
| 9 | # on the apps' zone, and an API token for the deployments service. Set |
| 10 | # CLOUDFLARE_EMAIL and CLOUDFLARE_API_KEY (a Global API Key) and this |
| 11 | # script makes both; otherwise it says what to make by hand. |
| 12 | set -euo pipefail |
| 13 | |
| 14 | ROOT="$(cd "$(dirname "$0")/.." && pwd)" |
| 15 | export CLOUDFLARE_API_TOKEN="${CLOUDFLARE_DEPLOY_TOKEN:-}" |
| 16 | ZONE="${G1T_APPS_ZONE:-g1t.page}" |
| 17 | NAMESPACE="g1t-deployments" |
| 18 | TOKEN_FILE="$ROOT/.credentials/deployments-cloudflare-token.txt" |
| 19 | w() { npx wrangler "$@"; } |
| 20 | |
| 21 | cd "$ROOT/services/deployments" |
| 22 | |
| 23 | echo "== D1 database" |
| 24 | if grep -q TO_BE_CREATED wrangler.jsonc; then |
| 25 | id=$(w d1 create g1t-deployments </dev/null 2>&1 | grep -oE '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}' | head -1 || true) |
| 26 | [ -n "$id" ] || { echo "Could not create the database; is it there already? (npx wrangler d1 list)"; exit 1; } |
| 27 | sed -i "s/TO_BE_CREATED/$id/" wrangler.jsonc |
| 28 | echo "Created $id and wrote it into services/deployments/wrangler.jsonc. Commit that." |
| 29 | else |
| 30 | echo "Already set." |
| 31 | fi |
| 32 | |
| 33 | echo "== Dispatch namespace and event queue" |
| 34 | w dispatch-namespace list 2>/dev/null | grep -q "$NAMESPACE" || w dispatch-namespace create "$NAMESPACE" |
| 35 | w queues list 2>/dev/null | grep -q g1t-events-deployments || w queues create g1t-events-deployments |
| 36 | |
| 37 | echo "== DNS record and the service's token" |
| 38 | if [ -n "${CLOUDFLARE_API_KEY:-}" ] && [ -n "${CLOUDFLARE_EMAIL:-}" ]; then |
| 39 | G1T_APPS_ZONE="$ZONE" TOKEN_FILE="$TOKEN_FILE" python "$ROOT/scripts/cloudflare-setup.py" |
| 40 | else |
| 41 | cat <<EOF |
| 42 | Set CLOUDFLARE_EMAIL and CLOUDFLARE_API_KEY to do this for you, or by hand: |
| 43 | 1. On $ZONE, add a proxied DNS record: type AAAA, name *, content 100:: |
| 44 | 2. Create an API token with Workers Scripts: Edit and Account Analytics: |
| 45 | Read on the account, and save it as one line in |
| 46 | $TOKEN_FILE |
| 47 | EOF |
| 48 | fi |
| 49 | |
| 50 | if [ -f "$TOKEN_FILE" ]; then |
| 51 | echo "== Storing the token as the deployments service's secret" |
| 52 | w deploy |
| 53 | tr -d '\r\n' <"$TOKEN_FILE" | w secret put CLOUDFLARE_API_TOKEN |
| 54 | fi |
| 55 | echo "== Done. Now: scripts/deploy.sh" |