how-to deployer

Runbook — Provision a new per-country deployment (Coolify)

Provision one OpenGov deployment (a country × project, keyed by code, e.g. let-cob) onto a Coolify-managed server. Provisioning acts on machinery and its actor is the operator; it ends with a running but empty deployment. What the country’s own administrator then does in the browser to make it fit to use is country onboarding, which is not in this runbook. Both words: docs/reference/plain-vocabulary.md. Pairs with docs/specs/2026-06-07-per-country-deployment-automation.md and docs/plans/2026-06-07-per-country-deployment-automation-p0-p1.md. For the how-it-works view (artifact, self-bootstrap, host-based serving, gotchas) see docs/reference/deployment-architecture.md.

What is automated vs. what you do by hand

StepAutomated?
Schema migration + registry-row seed at boot✅ the init compose service (opengov.bootstrap_deployment)
Import and independently reconcile staff and applicant realms at boot✅ both image imports and init-keycloak
Push env + secrets to Coolify, set domain, deploy, wait✅ scripts/provision_country.py
Create the Coolify project / environment / GitHub App❌ manual, Coolify UI (browser OAuth — cannot be scripted)
Place the scanner rules file (deploy/clamav/rules/opengov.yar) on the host❌ manual, once before first deploy (step 3b)
Inject KEK-tier secrets into the container❌ manual, out-of-band (by design — never via Coolify)
Confirm a real SPA login works❌ manual
Install applicant limits and refuse public admin paths✅ login-service labels in Compose and Swarm

One-time prerequisites (per Coolify server)

  1. A Coolify v4 server reachable at COOLIFY_BASE_URL, with an API token (COOLIFY_TOKEN, a fleet-tier secret — read into the env, never commit).
  2. A GitHub App connected to Coolify (Coolify UI → Sources → GitHub App). This requires a browser OAuth flow and cannot be scripted — do it once.
  3. sops + age installed on the operator workstation.

Per-deployment onboarding

1. Create the artifact

mkdir -p deployments/<code>
cp deployments/tst-dep/config.yaml deployments/<code>/config.yaml
# edit: code, country_iso2, project_slug, display_name, timezone, locales,
#       wildcard_base (e.g. services.example.gov),
#       operational_logs.retention_days (see below),
#       coolify.{project_uuid,server_uuid,github_app_uuid},
#       coolify.git_repository / git_branch

scripts/scaffold_deployment.py writes the same file with every field validated before anything lands on disk — prefer it to copying the fixture.

Every default deployment includes the staff opengov and public opengov-applicants realms. Scaffolded artifacts enable applicant trust and select the applicant portal issuer automatically; registration stays closed. Provisioning injects both issuer/audience settings, and init-keycloak independently reconciles both realms. The post-deploy smoke checks both discovery endpoints. For an existing deployment with historical applicant ownership, explicitly retain applicant_realm_enabled: false until the cutover inventory is resolved; both realms still provision and back up. Follow the applicant realm runbook before opening registration.

live_deployment defaults to true for every country deployment that serves real applicants. When live_deployment is true, the platform refuses to publish any procedure with an automatic step (D66). Pass --non-live to scripts/scaffold_deployment.py or set live_deployment: false in config.yaml for a sandbox, staging, or training deployment.

Step for a stack that is not live. docker-compose.yml and docker-stack.yml set OPENGOV_LIVE_DEPLOYMENT to true when the host gives no value. The value in config.yaml reaches a host only when an operator runs provisioning (src/opengov/platform/deployments/provision.py). So a sandbox, staging, or training stack reads true after its next deploy of such a file. Before that deploy, set OPENGOV_LIVE_DEPLOYMENT=false in the stored environment of that host.

operational_logs.retention_days is how long the platform keeps its own log files: the running commentary of what the software did (a request arrived, a job ran, something failed), under /var/log/opengov on the oplogs volume. It is not the audit record of what an officer decided, which is governed separately, and it does not reach a copy the country forwards to its own log collector — that copy is kept for as long as that collector is configured to keep it. The default is 90 days; a value outside the accepted range refuses the boot rather than being quietly clamped. Spec: docs/specs/2026-08-12-logging-spine.md.

The component hosts derive from wildcard_base via the fixed convention: smartrules. (editor), approval., applicant. (portal), smartlink., studio., login. (Keycloak), and mcp. — the assistants door, which serves no screen. Point a wildcard DNS *.<wildcard_base> at the server; the reverse proxy routes each host. provision_country.py sets every Coolify domain + the OIDC and assistants-door env automatically — no manual per-host wiring.

The code MUST match the regex ^[a-z]{2,3}-[a-z0-9]+(-[a-z0-9]+)*$ and the deployments registry row (the artifact IS the source of truth — the init service seeds the row from it at boot).

2. Per-deployment age key + generated secrets

age-keygen -o keys/<code>.agekey            # PRIVATE key — NEVER commit; escrow out-of-band
# copy the "# public key: age1..." line into a creation_rule in .sops.yaml
python scripts/generate_secrets.py <code>    # mints + SOPS-encrypts secrets.env

generate_secrets.py is the ceremony: it generates every secret, SOPS-encrypts secrets.env, and mints the deployment’s Sentinel keypair — the private key enters secrets.env (KEK-tier) and the public key is written to deployments/<code>/sentinel.pub.pem (a non-secret, COMMITTED artifact). It prints the KEK-tier key list and the Sentinel fingerprint (record it — you cross-check it when registering, step 7). Run it on a trusted machine, never on the deploy host.

secrets.env holds two tiers (the onboard CLI splits them):

  • Coolify tier (pushed): POSTGRES_PASSWORD, OPENGOV_API_CLIENT_SECRET, OPENGOV_SEED_ADMIN_PASSWORD (see below), …
  • KEK tier (NEVER pushed; inject out-of-band): OPENGOV_ENCRYPTION_KEY, OPENGOV_ANON_HASH_SALT, OPENGOV_VAULT_KEK_V*, OPENGOV_WM_BLIND_INDEX_KEY, OPENGOV_SENTINEL_SIGNING_KEY.

The pre-commit guard refuses to commit a plaintext secrets.env (or any private-key PEM). Never add a *_kms recipient to .sops.yaml — it breaks air-gap. Commit deployments/<code>/{config.yaml,secrets.env,sentinel.pub.pem} + the .sops.yaml rule, and open the onboarding PR (step 7 depends on it being merged).

First admin login. The realm imports with zero users, so set OPENGOV_SEED_ADMIN_PASSWORD in secrets.env to have the init service seed a first Keycloak login on boot (OPENGOV_SEED_ADMIN_EMAIL, default admin@opengov.local, with OPENGOV_SEED_ADMIN_ROLES, default admin). It is opt-in (no password → no account) and non-fatal (a KC hiccup never blocks boot); re-runs are idempotent. Without it, no one can log into the SPAs.

3. Create the Coolify project/env/app shell (UI, once per deployment)

In Coolify: create (or pick) the project + production environment; note the project_uuid / server_uuid / github_app_uuid into the artifact’s coolify: block. (App creation itself is automated in step 4.)

3b. Place the scanner rules file on the Coolify host

Coolify compose builds copy only docker-compose.yml to the host. They do not copy other repository files. Place deploy/clamav/rules/opengov.yar on the Coolify host before step 4 runs the first live deploy. Otherwise Docker creates an empty folder at that bind path and freshclam exits with code 78.

  1. Run --dry-run first to read the expected sha256 digest of deploy/clamav/rules/opengov.yar:

    python scripts/provision_country.py --dry-run deployments/<code>
    
  2. On the Coolify host, create deploy/clamav/rules/ inside the compose folder of the application. Copy deploy/clamav/rules/opengov.yar from the deployed commit into that folder.

  3. Match the sha256sum output on the host against the sha256 digest from step 1:

    sha256sum deploy/clamav/rules/opengov.yar
    

After the stack runs, scripts/release/check_scanner_rules.sh compares the repository copy, the host copy, and the loaded copy in clamav-db.

4. Dry-run, then onboard

python scripts/provision_country.py --dry-run deployments/<code>   # preview
export COOLIFY_BASE_URL=https://coolify.example  COOLIFY_TOKEN=…  # fleet-tier
export SOPS_AGE_KEY_FILE=keys/<code>.agekey
python scripts/provision_country.py deployments/<code>             # live

This find-or-creates the dockercompose app, pushes the Coolify-tier env + the four OPENGOV_*_URL (which the in-compose Keycloak --import-realm substitutes into redirect URIs), sets the 5 component domains, deploys, and waits.

5. Inject KEK-tier secrets out-of-band

The CLI prints the KEK-tier keys. Set them on the container env via your out-of-band mechanism (Coolify-mounted host env file / platform secret store) — not through the Coolify API. Until then, vault PII operations stay “broken at rest” by design (see scripts/backup.sh).

6. Verify (the /health gate proves only “process up”)

  • Watch the first deploy for an init failure or an opengov exit-78 restart loop — if you see one, the registry row was not seeded (check the init container logs + that deployments/<code>/config.yaml shipped in the image).
  • curl https://smartrules.<wildcard_base>/health → 200 (process up only).
  • Do a real SPA login — this is the only proof the Keycloak realm import substituted the redirect URIs correctly.
  • Check the security headers once — a content policy on the SPA shell, transport security on HTTPS responses, and the sign-in host’s own transport-security setting (the app middleware never sees login.<deployment>). Private-CA (step-ca) deployments opt out of transport security at onboarding. Walkthrough: docs/runbooks/security-headers.md.

8. Check the default login protections

The login-service labels install the applicant limits and refuse /admin on the public login host. Provisioning derives OIDC_PROXY_HOST from the deployment artifact. Provisioning also preserves Compose variables in Coolify labels. Dedicated public routes keep path-specific middleware off normal sign-in requests. Coolify keeps its normal domain routes, while the protection routes take priority. Compose and Swarm declare the same rules.

Run python scripts/smoke_deployment.py <code> from your workstation. Check 8 must report refused (403) for both admin paths. Check the applicant request budgets through the public host before opening registration. The procedure is in the applicant runbook.

For older deployments, reprovision with the current files. Remove older login-protection files from the proxy after the labels take effect. The renderers remain available for a temporary fix before that deploy.

9. Reach the admin console through an SSH tunnel

Step 4 gives the login service the setting KC_HOSTNAME_ADMIN=http://localhost:18088. The console then sends its API calls to that address. So your tunnel must use the local port 18088.

  1. Get the address of the login service container. <project> is the Compose project of the deployment. On Coolify it is the identifier of the application. The labels select one container. A name filter matches parts of names, so it can select the login service of another deployment.

    ssh <operator>@<host> "docker ps -q -f label=com.docker.compose.project=<project> -f label=com.docker.compose.service=oidc" > oidc-id
    wc -l < oidc-id                              # must be 1. Otherwise stop.
    OIDC_IP=$(ssh <operator>@<host> "docker inspect -f '{{range .NetworkSettings.Networks}}{{println .IPAddress}}{{end}}' $(cat oidc-id)" | head -1)
    
  2. Open the tunnel. Keep this command open while you work:

    ssh -N -L 18088:"$OIDC_IP":8080 <operator>@<host>
    
  3. In your browser, open http://localhost:18088/admin/master/console/.

Each deploy gives the container a new address. After a deploy, do step 1 again. A script that calls the admin API uses the same tunnel. Give it --oidc-base http://localhost:18088.

Handover to the country’s govtech team

In plain words. Everything above sets a deployment up. This section is how it stops being ours. A team that has watched us do everything owns nothing — so every step below is performed by their hands while we watch, never the reverse.

Handover is complete when the country team has restored a backup and performed one upgrade without us driving.

That sentence is the acceptance test of the onboarding itself. It can start from the project’s earliest stages: every step here works on a deployment with no production data yet, which is precisely when practising them is cheap.

Before the first country: complete the signing key set

Do this before their first checkout, not after. A deployment takes its trust set from the checkout it is installed from. Keys committed beforehand arrive free; keys committed afterwards need a signed release to carry them out, and the recovery key in particular is one you cannot add after you need it.

The platform runs on a single signing key today, which is deliberate and safe while our own sandbox is the only thing consuming releases (owner decision, 2026-08-15). A country ends that. Three things must exist first — the full reasoning is docs/runbooks/release-signing.md part 6:

  • A second holder, with their public half committed. One holder is a single point of failure for shipping at all; with a country live, “the only person who can sign is unreachable” is an outage with no workaround.
  • An offline recovery key, committed. The case where every signing key is lost has no automatic way back, and this key is only useful if the country’s first install already trusts it.
  • Custody split. The recovery key’s private half in a safe — not a laptop, not a password manager — with its passphrase held by someone who is neither signer.

Until all three are committed, a country may be set up but must not be handed over: the trust ceremony below would be teaching them a key set we already know is incomplete.

1. Credential custody

The read-only deploy key is minted in their presence, named opengov-<code>, and they record its fingerprint in their own artifact — not only in ours.

They should leave knowing exactly what it can do: it reads everything in this repository and writes nothing. It cannot push, cannot mint a release, and cannot move a channel. If it leaks, it is revoked from GitHub’s key list, which is the register.

2. Trust ceremony

They check the fingerprints of the keys in deploy/registry/trusted-keys/ against a copy that did not travel with the code — read out on a call, or by any route independent of the checkout — and they keep that copy.

Why it matters, in one sentence: a first install has no previous release to verify against, so the trust set that arrives in its own checkout is the trust root, and an out-of-band fingerprint check is the cheap hardening for that. Detail: docs/runbooks/release-signing.md part 4.

3. Backup ownership

They run sudo bash scripts/install-backup-timer.sh themselves, then bash scripts/restore_drill.sh.

A backup nobody on their team has restored is not yet their backup. The drill proves both directions — that a good bundle restores, and that a corrupted one is refused rather than half-applied.

4. Subscription

They set notify on stable in deployments/<code>/config.yaml, install the release timer with sudo bash scripts/install-release-timer.sh, and find the release field in GET /health.

Point out what it says when nothing is wrong: not_configured before the timer, unreachable when they cannot reach us. Neither is an outage, and the health verdict never moves because of either — losing contact with us must never degrade their deployment.

5. Offline page

They run sudo bash scripts/install-offline-page.sh themselves — it renders the “service unavailable” page (their own wordmark and emblem baked in) and its Traefik route from their own committed config.yaml, installs a host systemd service outside the application’s compose stack, and proves the page answers before reporting success (docs/runbooks/offline-page.md).

Once that installer has reported success, re-run the smoke check with the offline-page checks turned on — this is the one proof that a country cannot be declared provisioned without the page:

python scripts/smoke_deployment.py <code> --check-offline-page

Honest limit worth saying out loud: if the container engine itself is down on their host, there is no proxy and no page — this covers a redeploy or crash of the application, not the whole host going dark.

6. One real upgrade

They perform a full upgrade per docs/runbooks/upgrade-contract.md, in order: back up, scripts/release/verify_checkout.sh v<version>, checkout, rebuild, health check. We observe and answer questions; we do not touch the keyboard.

7. The stop

They exercise hold once and lift it:

printf 'on_new_release: hold\n' > deployments/<code>/release.local.yaml
sudo systemctl start opengov-release-check.service   # /health now reports the hold
rm deployments/<code>/release.local.yaml             # and lifting it is a deletion

This is the step teams skip and later need at the worst moment. It is deliberately a file on their machine, not a setting in the repository: the committed artifact only reaches them by upgrading, and a stop delivered by the thing it stops is a contradiction.


Pre-deploy data check (databases that already carry org-chart rows)

Skip this section on a fresh install — there is nothing to check. It applies when the platform is pointed at a database that already carries rows in the org chart (the wm_government table — the country’s list of its government bodies, where each body is known by its code and names the body it sits inside): a restore, a hand-seeded chart, or data loaded before the platform enforced the chart’s shape.

Migrations enforce that shape: every body’s code is unique (uq_wm_government_institution_code) and every parent reference must be a real code (the foreign key fk_wm_government_parent_institution). Run the three read-only checks below before alembic upgrade heads. Any row a check returns must be fixed by hand first — otherwise the migration refuses to run, or worse, runs cleanly over data that already lies.

# 1. Dangling parents — every parent reference that is no body's code.
#    The foreign key refuses the migration while any of these exist.
docker exec opengov-db-1 psql -U opengov -d opengov -c "
SELECT DISTINCT g.parent_institution
FROM wm_government g
WHERE g.parent_institution IS NOT NULL
  AND NOT EXISTS (
    SELECT 1 FROM wm_government p
    WHERE p.institution_code = g.parent_institution
  );"

# 2. Duplicate codes — the same code carried by two bodies.
#    The unique constraint refuses the migration while any of these exist.
docker exec opengov-db-1 psql -U opengov -d opengov -c "
SELECT institution_code, COUNT(*)
FROM wm_government
WHERE institution_code IS NOT NULL
GROUP BY institution_code
HAVING COUNT(*) > 1;"

# 3. Bodies with no parent — expected to list ONLY the country's root
#    body (the one everything else sits inside). Any other row is a body
#    whose parent was never recorded; it would float at the chart's top
#    level. Fix the data, or confirm the country really has several roots.
docker exec opengov-db-1 psql -U opengov -d opengov -c "
SELECT institution_code, institution_name
FROM wm_government
WHERE parent_institution IS NULL;"

While at it, eyeball bodies with no code at all (institution_code IS NULL) — the code is how everything else points at a body, so a codeless row is unreferenceable data and should be fixed the same way. All four queries are reads; they change nothing.

Recovery

  • exit-78 restart loop: the deployments row is missing. Inspect the init container logs; confirm OPENGOV_DEPLOYMENT_CODE matches a committed deployments/<code>/config.yaml. Re-deploy (init is idempotent).
  • Bad deploy: redeploy the previous image tag (Coolify) — the registry row and Postgres are untouched by an app-image rollback.
  • Backups: scripts/backup.sh (pg_dump + KC realm export; KEK kept out-of- band) / scripts/restore.sh.

Known gaps (verify before production)

  • Coolify endpoint shapes in coolify_client.py are confirmed against the Coolify v4.x published openapi.json (2026-06-07). The application status strings used by wait_for_deploy are NOT enumerated in the spec — sanity-check the substring heuristic against the first real deploy (GET /api/v1/applications/{uuid}).
  • The Coolify API token and the GitHub App connection are created in the Coolify UI (browser) — these cannot be scripted; do them once per server.
  • SOPS major version differs pre/post 3.8 on the encrypt/decrypt subcommand — pin the operator’s version.