This systemd timer setup is a manifest-driven version of the deploy script proven on the larger moving 15 WordPress sites to Cloudflare Workers migration, where both the build and the hosting moved onto infrastructure the owner controls.
Why use systemd timers instead of hosted CI?
systemd timers are a reasonable CI replacement when the build is short, the sites are few and the machine already runs. A timer on hardware you control has no queue, no per-minute charge and no separate secrets store to keep in sync.
The trade-off is that you own the failure modes. Hosted builds give you a clean image every time; a timer gives you whatever Node, pnpm and environment the machine had at 03:00. Most of the work in cf-deploy is making that environment explicit.
| Trigger | Latency after a push | Build environment | Main failure mode |
|---|---|---|---|
| Hosted Workers Builds (Cloudflare Workers Builds) | Queued, then a fresh image | Reproducible, managed by the provider | Queue time, config drift between dashboard and repo |
| systemd timer plus wrangler | Up to the poll interval | Whatever the host has, unless pinned | Node and env drift on the host |
| Git webhook to a local runner | Seconds | Whatever the host has | The listener is another service to keep alive |
Which should you choose? Use hosted builds when the site changes often, several people push, or the build needs a clean environment. Use a timer when the fleet is small, the machine is already on, and you want the deploy to survive a provider outage. A webhook is better than polling when latency matters; polling is simpler when the repository is private and the runner sits behind a private network.
The manifest is the whole configuration
The manifest is a nine-column TSV file because a deploy should be data, not a script edit. Each row names a site, its repo, branch, working directory, build command, deploy command, watched paths, output directory and an optional content glob for scheduled posts.
The columns that carry the design:
watch_pathsdecides whether a change is relevant. A shared package change rebuilds every site that imports it; a post in one site’s content directory rebuilds only that site.dist_diris hashed after the build. If the hash matches the last deployed one, the upload is skipped even when the commit changed.due_globis checked by a small Python helper for non-draft posts whose publish day in America/Chicago has arrived. That is what the nightly timer drives.- One checkout per repo, not per site, with a
flockper repo. Two sites built from the same checkout run sequentially and each build starts from a clean output directory.
That last rule is not cosmetic. Building two brands from one monorepo in parallel can produce a mix of the two outputs; serializing them is cheaper than debugging the result.
What does one poll run do?
A poll run is a fixed sequence: lock, sync, compare, install if needed, build, hash, deploy, record. Every step writes state so the next run can decide without guessing.
- Take the repo lock. If another run holds it, exit without building.
- Fetch and reset.
git fetchthenreset --hard origin/<branch>. The checkout is a deploy mirror; nobody edits it. - Compare. Diff the last deployed commit against
HEADwithgit diff --name-onlyand test the result againstwatch_paths. On the first run, with no state, build. - Install only when the lockfile changed. The lockfile hash lives in the state file, so a normal run skips the install.
- Clean and build. Remove
dist_dirfirst so a stale artifact cannot survive a failed build. - Hash the output. A sorted SHA-256 over every file in
dist_dir. - Deploy only if the hash changed. Run the deploy command — usually
wrangler deploy(Wrangler commands) — with the credentials file loaded, and record the commit and hash only on success. - Write the heartbeat. Every run updates it, whether or not anything deployed.
State sits under the user’s state directory: a heartbeat timestamp, one line per failure in alerts.log, a per-site state file, and per-run logs with the newest 30 kept per site. That is enough for an external watcher to tell “no changes” from “the timer stopped” without reading the code.
Running user timers without a login session
User timers run without a login session when lingering is enabled for the account. loginctl enable-linger spawns a user manager at boot and keeps it after logout, which is what lets a user service keep running on a headless box (loginctl).
sudo loginctl enable-linger deploy
systemctl --user enable --now cf-deploy.timer cf-deploy-nightly.timer
A user unit is the right scope here. The deploy runs as the account that owns the checkout and the Cloudflare token, so it needs no root and cannot touch another user’s files. The alternative — a system unit with User= and a copied environment — adds configuration without adding safety.
Timer semantics matter more than they look. OnUnitActiveSec=2min is relative to the last time the service was activated, not to the wall clock, and AccuracySec defaults to one minute (systemd.timer). A two-minute timer is therefore “about every two to three minutes”, with the exact point randomised per host. That is fine for a deploy poller and wrong for anything that must fire at a precise time.
The nightly timer is a calendar timer at 00:05 America/Chicago with --force, limited to sites that have a due_glob. It exists because a post scheduled for tomorrow should go out without a human at the keyboard, and because the poll alone would only notice it on the next commit.
Pinning Node per unit
Pinning Node per unit is what separates “works in my shell” from “works at 03:00”. The first unattended builds failed on the system Node 22.22.1 because the build’s engine check required 22.23.4. The interactive shell had the nvm version on PATH; systemd did not.
The fix is a drop-in at ~/.config/systemd/user/cf-deploy.service.d/node.conf, not an edit to the unit:
[Service]
Environment=PATH=/home/deploy/.nvm/versions/node/v22.23.4/bin:/home/deploy/.local/bin:/usr/local/bin:/usr/bin:/bin
Two details. systemd does not expand $HOME or run a shell in Environment=, so the path must be absolute (systemd.exec). And the drop-in survives a package upgrade or a regenerated unit, which an edit to the unit itself would not.
The engine check comes from ordinary package metadata: a package declares the Node range it supports in engines, and the install or build stops when the running version falls outside that range (npm package.json). The failure only appears when the unit runs, which is exactly why the first deploy test should run through systemd rather than from a shell.
Reading env files that are not shell
Reading env files safely means not sourcing them. These files are in the format Docker accepts for env_file, where a value can be unquoted and contain spaces or angle brackets (Docker environment variables). That is not valid shell.
The first version used the usual idiom, set -a; . "$ENV_FILE"; set +a, and it broke on values with spaces and </>: source parses the file as shell, so an unquoted space splits words and a < becomes a redirection (Bash builtins). The loader now reads line by line and exports the key and the rest of the line verbatim:
while IFS= read -r line || [[ -n $line ]]; do
[[ $line =~ ^([A-Za-z_][A-Za-z0-9_]*)=(.*)$ ]] || continue
export "${BASH_REMATCH[1]}=${BASH_REMATCH[2]}"
done < "$ENV_FILE"
The regex takes everything after the first =, so spaces, angle brackets and $ survive intact. Blank lines and comments fail the match and are skipped. The values are exported for the deploy command, and nothing in the file is ever evaluated as shell code.
Rewriting the files as shell would have been the other fix. It was rejected because the same files are consumed by Docker Compose elsewhere; one format, one source of truth.
Secrets versus plain vars
Secrets versus plain vars is a binding-namespace problem, not an upload problem. Cloudflare Workers keep vars and secrets in the same namespace, so a key that already exists as a plain variable cannot also be uploaded as a secret (Workers secrets).
A bulk secret upload therefore failed with Binding name already in use on the keys already defined in wrangler.jsonc. The fix is to read the vars block first and exclude those keys from the bulk upload, leaving the rest to be set as secrets. It is a short guard that turns a failed deploy into a clean one.
Binding names are unique across both kinds within a Worker, and the deploy tooling enforces it.
What broke and what we changed
Three failures and one near miss shaped the deployer.
Node drift. The system Node was 22.22.1; the build wanted 22.23.4 or newer. Interactive runs passed because nvm’s PATH was loaded in the shell, and unattended runs failed because systemd starts with a minimal environment. The drop-in above fixed it. The broader change was to test every unit through systemctl --user start, not by running the script by hand.
Env parsing. Sourcing a Docker-format env file broke on values with spaces and angle brackets. The line-by-line loader replaced it. The new loader also stopped a malformed line from executing as a command, which the source version would have done.
Secret collisions. The first bulk upload tried to create secrets for keys already present as plain vars and stopped on Binding name already in use. Excluding the vars keys fixed it. The rule now lives in the upload script, not in a runbook someone has to remember.
Two brands, one checkout. The manifest allows two sites from one repo, which is a collision waiting to happen: both builds write a dist/ and one can consume the other’s output. The per-repo flock and a clean dist_dir before each build serialize them. The manifest still allows both rows; the lock makes them safe.
Related
- Moving 15 WordPress sites to Cloudflare Workers — the migration that made a static deploy pipeline worth building.
- When a Worker never runs: static assets and run_worker_first — the routing bug that only appeared after deploy.
- A remote BuildKit server cut our builds by 62% — the other build-time investment in this infrastructure.
- One GPU, three inference stacks — the same unit-file discipline applied to a shared GPU.
- Infrastructure and edge work — the discipline this project sits under.
Frequently asked questions
Do systemd timers replace CI entirely?
For a small static fleet, yes: a timer, a manifest and wrangler cover build, deploy and scheduling. They do not replace the parts of CI that give you a clean environment, parallel test runners or a shared artifact store. The timer is a deploy mechanism, not a test platform.
How often does cf-deploy poll?
Every two minutes by timer configuration, though AccuracySec defaults to one minute, so the effective interval is roughly two to three minutes. The poll is cheap when nothing changed: a fetch, a diff and a heartbeat write. The nightly pass at 00:05 handles posts that become due without a commit.
What happens when a build fails?
The failure is written to alerts.log with the site, step, exit code and the path to that run's log. The other sites still deploy. The failed site keeps its previous state, so the next poll retries it rather than treating the failure as a successful deploy.
Why not deploy from a git webhook instead?
A webhook gives lower latency and is the better choice when a push should deploy within seconds. It also adds a listener that has to stay up and authenticate. Polling a private repository from a machine already on the network avoids that service and is simple to reason about. For a site fleet that changes a few times a day, the latency does not matter.
Why run the timer as a user service?
Because the deploy needs the user's checkout, the user's Cloudflare token and nothing else. A user service with lingering runs at boot without root, and a compromise of the deploy account does not hand over the machine. A system service that runs as root would give the deploy far more privilege than it needs.
How do you pin Node for a systemd unit?
Use a drop-in with an absolute PATH to the Node version you want, then systemctl --user daemon-reload. Do not rely on nvm's shell hooks: systemd does not source .bashrc, and Environment= does not expand $HOME. Check the version from inside the unit with a one-shot node --version service before trusting a deploy.
Can one timer deploy several sites from one repo?
Yes. The manifest allows several rows with the same repo and different site_dir values. They share one checkout and one lock, so they build sequentially, and each row's watch_paths decide whether it rebuilds. That is how a monorepo ships several domains without a separate pipeline per domain.
