Merge pull request #116 from hazre/feat/cloudflare-workers-iac

feat: add Cloudflare Workers IaC and deployment workflow
This commit is contained in:
7w1 authored and GitHub committed 2026-03-04 21:21:18 -06:00
commit aa9f64fee7
20 files changed
+1884 -70

No files matched your search

+36
View File
@@ -0,0 +1,36 @@
name: Prepare OpenTofu Deployment
description: Prepares OpenTofu in infra/web.
inputs:
opentofu-version:
description: The OpenTofu version to install.
required: false
default: '1.11.5'
runs:
using: composite
steps:
- name: Setup app and build
uses: ./.github/actions/setup
with:
build: 'true'
- name: Setup OpenTofu
uses: opentofu/setup-opentofu@9d84900f3238fab8cd84ce47d658d25dd008be2f # v1.0.8
with:
tofu_version: ${{ inputs.opentofu-version }}
- name: Check formatting
shell: bash
working-directory: ${{ github.workspace }}/infra/web
run: tofu fmt -check
- name: Initialize OpenTofu
shell: bash
working-directory: ${{ github.workspace }}/infra/web
run: tofu init -input=false -reconfigure
- name: Validate configuration
shell: bash
working-directory: ${{ github.workspace }}/infra/web
run: tofu validate -no-color
+40
View File
@@ -0,0 +1,40 @@
name: Setup App
description: Sets up Node.js, installs dependencies, and optionally builds the app.
inputs:
install-command:
description: Command used to install dependencies.
required: false
default: npm ci
build:
description: Whether to build the app after installing dependencies.
required: false
default: 'false'
build-command:
description: Command used when build is enabled.
required: false
default: npm run build
runs:
using: composite
steps:
- name: Setup node
uses: actions/setup-node@53b83947a5a98c8d113130e565377fae1a50d02f # v6.3.0
with:
node-version-file: '.node-version'
cache: 'npm'
- name: Install dependencies
shell: bash
working-directory: ${{ github.workspace }}
run: ${INPUTS_INSTALL_COMMAND}
env:
INPUTS_INSTALL_COMMAND: ${{ inputs.install-command }}
- name: Build app
if: ${{ inputs.build == 'true' }}
shell: bash
working-directory: ${{ github.workspace }}
run: ${INPUTS_BUILD_COMMAND}
env:
INPUTS_BUILD_COMMAND: ${{ inputs.build-command }}
@@ -0,0 +1,80 @@
name: Cloudflare Infra
on:
pull_request:
paths:
- 'infra/web/**'
- '.github/workflows/cloudflare-web-deploy.yml'
- '.github/actions/prepare-tofu/**'
- '.github/actions/setup/**'
push:
branches:
- dev
workflow_dispatch:
env:
CLOUDFLARE_API_TOKEN: ${{ secrets.TF_CLOUDFLARE_API_TOKEN }}
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
TF_VAR_workers_message: ${{ github.event_name == 'pull_request' && github.event.pull_request.title || github.event.head_commit.message || github.sha }}
TF_VAR_account_id: ${{ secrets.TF_VAR_ACCOUNT_ID }}
TF_VAR_zone_id: ${{ secrets.TF_VAR_ZONE_ID }}
TF_HTTP_ADDRESS: ${{ secrets.TF_HTTP_ADDRESS }}
TF_HTTP_LOCK_ADDRESS: ${{ secrets.TF_HTTP_LOCK_ADDRESS }}
TF_HTTP_UNLOCK_ADDRESS: ${{ secrets.TF_HTTP_UNLOCK_ADDRESS }}
TF_HTTP_USERNAME: ${{ secrets.TF_HTTP_USERNAME }}
TF_HTTP_PASSWORD: ${{ secrets.TF_HTTP_PASSWORD }}
TF_HTTP_LOCK_METHOD: 'POST'
TF_HTTP_UNLOCK_METHOD: 'DELETE'
TF_HTTP_RETRY_WAIT_MIN: '5'
concurrency:
group: cloudflare-infra
cancel-in-progress: false
jobs:
plan:
if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository
runs-on: ubuntu-latest
permissions:
contents: read
pull-requests: write
defaults:
run:
working-directory: infra/web
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Prepare OpenTofu deployment
uses: ./.github/actions/prepare-tofu
- name: Comment PR plan
uses: dflook/tofu-plan@3f5dc358343fb58cd60f83b019e810315aa8258f # v2.2.3
with:
path: infra/web
label: production
apply:
if: (github.event_name == 'push' && github.ref_name == 'dev') || github.event_name == 'workflow_dispatch'
runs-on: ubuntu-latest
permissions:
contents: read
defaults:
run:
working-directory: infra/web
steps:
- name: Checkout repository
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Prepare OpenTofu deployment
uses: ./.github/actions/prepare-tofu
- name: Plan infrastructure
run: tofu plan -input=false -no-color
- name: Apply infrastructure
run: tofu apply -input=false -auto-approve
+17 -27
View File
@@ -15,13 +15,10 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup node
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
with:
node-version-file: '.node-version'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Setup app
uses: ./.github/actions/setup
- name: Check formatting
run: npm run fmt:check
@@ -35,13 +32,10 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup node
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
with:
node-version-file: '.node-version'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Setup app
uses: ./.github/actions/setup
- name: Run ESLint
run: npm run lint
@@ -55,13 +49,10 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup node
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
with:
node-version-file: '.node-version'
cache: 'npm'
- name: Install dependencies
run: npm ci
- name: Setup app
uses: ./.github/actions/setup
- name: Run TypeScript typecheck
run: npm run typecheck -- --pretty false
@@ -75,12 +66,11 @@ jobs:
uses: actions/checkout@de0fac2e4500dabe0009e67214ff5f5447ce83dd # v6.0.2
with:
persist-credentials: false
- name: Setup node
uses: actions/setup-node@6044e13b5dc448c55e2357c09f80417699197238 # v6.2.0
- name: Setup app
uses: ./.github/actions/setup
with:
node-version-file: '.node-version'
cache: 'npm'
- name: Install dependencies
run: npm ci --ignore-scripts
install-command: npm ci --ignore-scripts
- name: Run Knip
run: npm run knip
+12 -1
View File
@@ -6,4 +6,15 @@ devAssets
.DS_Store
.idea
.env
.env
.wrangler
.dev.vars*
.terraform/
*.tfstate
*.tfstate.*
*.tfvars
!*.tfvars.example
*.tfbackend
!*.tfbackend.example
crash.log
+4
View File
@@ -77,3 +77,7 @@ To build the app:
```sh
npm run build # Compiles the app into the dist/ directory
```
## Deployment and infrastructure
Deployment workflows and infrastructure details live in
[`infra/README.md`](infra/README.md).
+104
View File
@@ -0,0 +1,104 @@
# Infrastructure
`infra/web` manages the Cloudflare Worker, immutable Worker versions, the live
production deployment, and the production custom domain.
Prerequisites:
- OpenTofu `1.11.x` installed locally
- Node.js/npm installed locally so you can build `dist/` before Worker uploads
- A Cloudflare account with the target zone already onboarded to Cloudflare
- A GitLab project to store the OpenTofu state
- A GitLab access token that can read and write that project's OpenTofu state
Required GitHub repository secrets:
- `TF_CLOUDFLARE_API_TOKEN`
- `TF_VAR_ACCOUNT_ID`
- `TF_VAR_ZONE_ID`
- `TF_HTTP_ADDRESS`
- `TF_HTTP_LOCK_ADDRESS`
- `TF_HTTP_UNLOCK_ADDRESS`
- `TF_HTTP_USERNAME`
- `TF_HTTP_PASSWORD`
The workflows map those secrets onto the actual runtime environment variable names
that Cloudflare and OpenTofu expect.
Cloudflare API token permissions:
- `Account > Workers Scripts > Edit`
- Scope the token to the specific Cloudflare account that owns the Worker.
- Scope the token to the specific zone that serves `app.sable.moe`.
- Do not grant Pages or DNS edit permissions here. The Worker script upload and
custom-domain attach endpoints used by this repo accept Workers Scripts Write, and
Cloudflare creates the DNS record for the Worker custom domain automatically.
GitLab access token permissions:
- `api`
Helpful reference links:
- Create the main Cloudflare API token:
https://developers.cloudflare.com/fundamentals/api/get-started/create-token/
- Find your account ID and zone ID:
https://developers.cloudflare.com/fundamentals/account/find-account-and-zone-ids/
- GitLab-managed OpenTofu state:
https://docs.gitlab.com/user/infrastructure/iac/terraform_state/
Local setup:
1. Copy `terraform.tfvars.example` to `terraform.tfvars` and fill in shared values.
2. Copy `gitlab.http.tfbackend.example` to `gitlab.http.tfbackend` and fill in the
GitLab project ID, state name, and username.
3. Run `npm ci` from the repo root.
4. Export the GitLab access token as the backend password.
5. Export the Cloudflare API token for OpenTofu.
6. Run `npm run build` before `tofu plan` or `tofu apply`, because
`cloudflare_worker_version` uploads the built `dist/` assets.
7. Initialize the backend.
Local OpenTofu production flow from the repo root:
```bash
npm run build
export TF_HTTP_PASSWORD="<your-gitlab-access-token>"
export CLOUDFLARE_API_TOKEN="<your-cloudflare-api-token>"
tofu -chdir=infra/web init -reconfigure -backend-config="../gitlab.http.tfbackend"
tofu -chdir=infra/web validate
tofu -chdir=infra/web plan -var-file="../terraform.tfvars"
tofu -chdir=infra/web apply -var-file="../terraform.tfvars"
```
Optional local OpenTofu deployment message:
```bash
export TF_VAR_workers_message="$(git log -1 --pretty=%s)"
tofu -chdir=infra/web apply -var-file="../terraform.tfvars"
```
If you already created local state before switching to GitLab state, use
`tofu -chdir=infra/web init -reconfigure -migrate-state -backend-config="../gitlab.http.tfbackend"`
once instead.
Preview builds:
- `infra/web/main.tf` enables preview URL capability with `subdomain.previews_enabled = true`.
- Previews are handled by Cloudflare Workers Builds, not GitHub Actions.
- Connect the repo once in Cloudflare Workers Builds.
- Set the Cloudflare Builds deploy command to `npx wrangler versions upload`.
- This disables automatic deployments while still allowing Cloudflare to build PRs/branches and save them as preview versions.
- That keeps Cloudflare from promoting `dev` commits to production. Production stays on the OpenTofu/GitHub Actions path in this repo.
```bash
npx wrangler versions upload
```
Production deploys:
- `.github/workflows/cloudflare-web-deploy.yml` comments PR plans for `infra/web` changes.
- That PR plan job only runs for same-repo PRs, not fork PRs, because it needs repo secrets.
- The same workflow applies production on pushes to `dev` or manual dispatch.
- `tofu apply` uploads `dist/` through `cloudflare_worker_version` and promotes it with `cloudflare_workers_deployment`.
- Production lives on `app.sable.moe`.
+7
View File
@@ -0,0 +1,7 @@
address = "https://gitlab.com/api/v4/projects/replace-with-gitlab-project-id/terraform/state/replace-with-gitlab-state-name"
lock_address = "https://gitlab.com/api/v4/projects/replace-with-gitlab-project-id/terraform/state/replace-with-gitlab-state-name/lock"
unlock_address = "https://gitlab.com/api/v4/projects/replace-with-gitlab-project-id/terraform/state/replace-with-gitlab-state-name/lock"
username = "replace-with-gitlab-username"
lock_method = "POST"
unlock_method = "DELETE"
retry_wait_min = 5
+4
View File
@@ -0,0 +1,4 @@
account_id = "replace-with-cloudflare-account-id"
zone_id = "replace-with-cloudflare-zone-id"
worker_name = "sable"
custom_domain = "app.sable.moe"
+19
View File
@@ -0,0 +1,19 @@
# This file is maintained automatically by "tofu init".
# Manual edits may be lost in future updates.
provider "registry.opentofu.org/cloudflare/cloudflare" {
version = "5.18.0"
constraints = "~> 5.0"
hashes = [
"h1:ny17Q/ce8iuHxppA/yIuRpCkVDtqhE+LDynWtv9/qwI=",
"zh:47e7bdfd8eddd2685f383269c0b6936ef62edd6d8383c8d7757b0cce0a689737",
"zh:aa23eb6aa128667883cabc449ceca4072d0181f574cd727e08ebd6d69a4bfd48",
"zh:c3da673e05d3bd933c82e2b6ba0f85aa23c5e24fadd3932f7c066314feeb65a3",
"zh:c59f07c017fc78b79e80554a0737c9db2a2e681c3e46ff637942d28d1f1a3924",
"zh:d559074612835a37fa684d8d7d0cf68911487b71f4067acc59069cb00bb8baf0",
"zh:e12290a4eda757c183a4258230245dd170f0def389c37eb771db144ce3b382dd",
"zh:ed47e484432ba1bbbb4802061f395ebd253ae8e20be9b72552d3d830fd2ca268",
"zh:f35e08d468408697b3e7c4a7f548b874141ac8f8d395ab8edded322201cc7047",
"zh:f809ab383cca0a5f83072981c64208cbd7fa67e986a86ee02dd2c82333221e32",
]
}
+3
View File
@@ -0,0 +1,3 @@
terraform {
backend "http" {}
}
+47
View File
@@ -0,0 +1,47 @@
resource "cloudflare_worker" "site" {
account_id = var.account_id
name = var.worker_name
subdomain = {
enabled = true
previews_enabled = true
}
}
resource "cloudflare_worker_version" "site" {
account_id = var.account_id
compatibility_date = "2026-03-03"
worker_id = cloudflare_worker.site.id
assets = {
directory = abspath("${path.module}/../../dist")
config = {
not_found_handling = "single-page-application"
}
}
}
resource "cloudflare_workers_deployment" "site" {
account_id = var.account_id
script_name = cloudflare_worker.site.name
strategy = "percentage"
annotations = var.workers_message == null ? null : {
workers_message = var.workers_message
}
versions = [{
percentage = 100
version_id = cloudflare_worker_version.site.id
}]
}
resource "cloudflare_workers_custom_domain" "site" {
account_id = var.account_id
environment = "production"
hostname = var.custom_domain
service = cloudflare_worker.site.name
zone_id = var.zone_id
depends_on = [cloudflare_workers_deployment.site]
}
+9
View File
@@ -0,0 +1,9 @@
output "custom_domain" {
description = "Custom domain attached to the Worker"
value = cloudflare_workers_custom_domain.site.hostname
}
output "worker_name" {
description = "Cloudflare Worker name"
value = cloudflare_worker.site.name
}
+3
View File
@@ -0,0 +1,3 @@
provider "cloudflare" {
# API token will be read from CLOUDFLARE_API_TOKEN environment variable
}
+10
View File
@@ -0,0 +1,10 @@
terraform {
required_version = "~> 1.11.0"
required_providers {
cloudflare = {
source = "cloudflare/cloudflare"
version = "~> 5.0"
}
}
}
+29
View File
@@ -0,0 +1,29 @@
variable "account_id" {
description = "Cloudflare Account ID"
type = string
sensitive = true
}
variable "custom_domain" {
description = "Custom domain attached to the Worker"
type = string
default = "app.sable.moe"
}
variable "worker_name" {
description = "Cloudflare Worker name"
type = string
default = "sable"
}
variable "workers_message" {
description = "Optional short message attached to Worker deployments"
type = string
default = null
}
variable "zone_id" {
description = "Cloudflare Zone ID"
type = string
sensitive = true
}
-36
View File
@@ -1,36 +0,0 @@
[[redirects]]
from = "/config.json"
to = "/config.json"
status = 200
[[redirects]]
from = "/manifest.json"
to = "/manifest.json"
status = 200
[[redirects]]
from = "/sw.js"
to = "/sw.js"
status = 200
[[redirects]]
from = "/pdf.worker.min.js"
to = "/pdf.worker.min.js"
status = 200
[[redirects]]
from = "/public/*"
to = "/public/:splat"
status = 200
[[redirects]]
from = "/assets/*"
to = "/assets/:splat"
status = 200
[[redirects]]
from = "/*"
to = "/index.html"
status = 200
force = true
+1448 -1
View File
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -83,6 +83,7 @@
"ua-parser-js": "^1.0.41"
},
"devDependencies": {
"@cloudflare/vite-plugin": "^1.26.0",
"@element-hq/element-call-embedded": "0.16.3",
"@esbuild-plugins/node-globals-polyfill": "^0.2.3",
"@eslint/compat": "2.0.2",
@@ -113,6 +114,7 @@
"vite-plugin-pwa": "^1.2.0",
"vite-plugin-static-copy": "^3.2.0",
"vite-plugin-svgr": "4.5.0",
"vite-plugin-top-level-await": "^1.6.0"
"vite-plugin-top-level-await": "^1.6.0",
"wrangler": "^4.70.0"
}
}
+9 -4
View File
@@ -12,6 +12,7 @@ import topLevelAwait from 'vite-plugin-top-level-await';
import { VitePWA } from 'vite-plugin-pwa';
import fs from 'fs';
import path from 'path';
import { cloudflare } from '@cloudflare/vite-plugin';
import buildConfig from './build.config';
const packageJson = JSON.parse(
@@ -56,10 +57,6 @@ const copyFiles = {
dest: '',
rename: 'pdf.worker.min.js',
},
{
src: 'netlify.toml',
dest: '',
},
{
src: 'config.json',
dest: '',
@@ -166,6 +163,14 @@ export default defineConfig({
type: 'module',
},
}),
cloudflare({
config: {
compatibility_date: '2026-03-03',
assets: {
not_found_handling: 'single-page-application',
},
},
}),
],
optimizeDeps: {
// Rebuild dep optimizer cache on each dev start to avoid stale API shapes.