API guides
Recipes
Copy-paste automations: CI deploys, automatic rollback, backups, chat commands and monitoring.
Every recipe uses three environment variables:
| Variable | Example |
|---|---|
ORCH_URL |
https://panel.example.com |
ORCH_TOKEN |
a personal access token, orch_โฆ |
SITE_ID |
the site's id, e.g. 12 โ it is in the site's URL in the panel and in GET /api/sites |
The shell scripts need bash, curl and jq, which are preinstalled on GitHub-hosted runners.
๐ Deploy from GitHub Actions
Deploy the exact commit that passed your tests, then wait for the result so the workflow fails when the deploy fails.
The deploy script
Save it as .github/scripts/orch-deploy.sh (or anywhere in your repository):
#!/usr/bin/env bash
# Deploy a commit to Orchestrator and wait for the result.
# Needs: ORCH_URL, ORCH_TOKEN, SITE_ID, and optionally REF (a commit, tag or branch).
set -euo pipefail
api() { curl -fsS -H "Authorization: Bearer $ORCH_TOKEN" "$@"; }
# The newest deployment before we start, to recognise ours if it gets queued.
last=$(api "$ORCH_URL/api/sites/$SITE_ID" | jq '.deployments[0].id // 0')
result=$(api -X POST "$ORCH_URL/api/sites/$SITE_ID/deploy${REF:+?ref=$REF}")
id=$(jq -r '.deploymentId // empty' <<<"$result")
[ -z "$id" ] && echo "Another deploy is running; ours is queued: $(jq -r .message <<<"$result")"
for _ in $(seq 1 180); do # up to 30 minutes
site=$(api "$ORCH_URL/api/sites/$SITE_ID")
if [ -n "$id" ]; then
deployment=$(jq -c --argjson id "$id" '.deployments[] | select(.id == $id)' <<<"$site")
else
deployment=$(jq -c --argjson last "$last" '[.deployments[] | select(.id > $last)] | min_by(.id) // empty' <<<"$site")
fi
status=$(jq -r '.status // "waiting"' <<<"${deployment:-null}")
case "$status" in
success)
echo "โ
Deployed $(jq -r .commit <<<"$deployment")"
exit 0 ;;
failed)
echo "โ Deploy failed. Last lines of the log:"
jq -r '.log // "" | split("\n") | .[-40:] | join("\n")' <<<"$deployment"
exit 1 ;;
esac
sleep 10
done
echo "Timed out waiting for the deploy." >&2
exit 1
How it works:
POST /api/sites/{id}/deploy?ref=<commit>starts the deploy and returns{"started": true, "deploymentId": 346}โ or{"queued": true, โฆ}when another deploy is running. A queued deploy later deploys the branch head, notref.GET /api/sites/{id}returns the site with its 20 newestdeployments; the script waits until ours issuccessorfailedand prints the end of the log on failure.- The deploy itself runs your test gate, health check and automatic rollback as configured for the site.
The workflow
Create a repository secret ORCH_TOKEN (Settings โ Secrets and variables โ Actions) and add .github/workflows/deploy.yml:
name: Deploy
on:
push:
branches: [main]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
# โฆ your tests โฆ
deploy:
needs: test
runs-on: ubuntu-latest
concurrency: production
steps:
- uses: actions/checkout@v4
- name: Deploy to Orchestrator
env:
ORCH_URL: https://panel.example.com
ORCH_TOKEN: ${{ secrets.ORCH_TOKEN }}
SITE_ID: 12
REF: ${{ github.sha }}
run: bash .github/scripts/orch-deploy.sh
Tip. If CI deploys for you, turn off the site's push-to-deploy webhook so a push does not deploy twice. Create the token on a developer account that only has access to this site.
๐ฆ GitLab CI and Bitbucket Pipelines
The same script works everywhere. Store ORCH_TOKEN as a masked, protected variable.
# .gitlab-ci.yml
deploy:
stage: deploy
image: alpine:3.20
rules:
- if: $CI_COMMIT_BRANCH == "main"
variables:
ORCH_URL: https://panel.example.com
SITE_ID: "12"
before_script:
- apk add --no-cache bash curl jq
script:
- REF=$CI_COMMIT_SHA bash scripts/orch-deploy.sh
# bitbucket-pipelines.yml
pipelines:
branches:
main:
- step:
name: Deploy
deployment: production
image: alpine:3.20
script:
- apk add --no-cache bash curl jq
- export ORCH_URL=https://panel.example.com SITE_ID=12
- REF=$BITBUCKET_COMMIT bash scripts/orch-deploy.sh
โญ๏ธ Deploy only when there is something new
GET /api/sites/{id}/deploy/pending compares the branch with the last successful deploy:
pending=$(curl -fsS -H "Authorization: Bearer $ORCH_TOKEN" "$ORCH_URL/api/sites/$SITE_ID/deploy/pending")
if [ "$(jq -r .upToDate <<<"$pending")" = "true" ]; then
echo "Nothing to deploy."
exit 0
fi
echo "Deploying $(jq '.commits | length' <<<"$pending") new commit(s):"
jq -r '.commits[] | " \(.hash) \(.subject) โ \(.author)"' <<<"$pending"
โช Roll back when your own checks fail
The panel already rolls back automatically when the site's health check fails. To roll back on your own smoke tests โ a checkout flow, an API contract โ run them after the deploy and switch back to the previous release when they fail:
#!/usr/bin/env bash
set -euo pipefail
api() { curl -fsS -H "Authorization: Bearer $ORCH_TOKEN" "$@"; }
if ./smoke-tests.sh; then
echo "Smoke tests passed."
exit 0
fi
# Releases are listed newest first; take the one right after the live one.
previous=$(api "$ORCH_URL/api/sites/$SITE_ID/releases" \
| jq -r '.releases as $r | ($r | map(.isCurrent) | index(true)) as $i | $r[$i + 1].name // empty')
if [ -z "$previous" ]; then
echo "No previous release to roll back to." >&2
exit 1
fi
echo "Smoke tests failed โ rolling back to $previous"
api -X POST "$ORCH_URL/api/sites/$SITE_ID/rollback" \
-H "Content-Type: application/json" \
-d "{\"release\":\"$previous\"}" | jq .
exit 1
A rollback only switches the current link back and restarts the queue workers โ it does not run migrations backwards or restore the database.
๐พ Nightly off-site backup
Copy each site's newest database backup to your S3 or R2 bucket every night. Configure the bucket once in Settings โ Integrations โ S3 / R2, and turn on the site's Backup Schedule so the panel makes the dumps.
#!/usr/bin/env bash
# Upload the newest database backup of a site to the S3/R2 bucket configured in the panel.
set -euo pipefail
api() { curl -fsS -H "Authorization: Bearer $ORCH_TOKEN" "$@"; }
newest=$(api "$ORCH_URL/api/sites/$SITE_ID/database/backups" \
| jq -r '.backups | sort_by(.createdAt) | last | .name // empty')
if [ -z "$newest" ]; then
echo "No backups yet โ turn on the site's Backup Schedule." >&2
exit 1
fi
api -X POST "$ORCH_URL/api/sites/$SITE_ID/database/backup/s3/$newest" | jq -r '"Uploaded to s3://\(.bucket)/\(.key)"'
Run it from cron on any machine โ after the panel's own backup has run:
30 3 * * * ORCH_URL=https://panel.example.com ORCH_TOKEN=orch_โฆ SITE_ID=12 /usr/local/bin/orch-backup.sh
To make a fresh dump first, call POST /api/sites/{id}/database/backup โ it returns the new filename. It is meant for small databases: the dump started through the API stops after 30 seconds, while scheduled backups have no such limit. To keep a copy outside your bucket, download a backup with GET /api/sites/{id}/database/backups/{filename}.
๐ฌ Deploy from Slack
A /deploy shop.example.com command for your team. Create a Slack app with a slash command pointing at this small service, and run it with SLACK_SIGNING_SECRET, ORCH_URL and ORCH_TOKEN set:
// slack-deploy.mjs โ node slack-deploy.mjs (Node 20+, npm install express)
import crypto from 'node:crypto';
import express from 'express';
const app = express();
app.use(express.urlencoded({ extended: false, verify: (req, _res, buf) => { req.rawBody = buf.toString(); } }));
const orch = (path, options = {}) =>
fetch(`${process.env.ORCH_URL}/api${path}`, {
...options,
headers: { Authorization: `Bearer ${process.env.ORCH_TOKEN}`, ...options.headers },
}).then(async (res) => ({ ok: res.ok, body: await res.json().catch(() => ({})) }));
function fromSlack(req) {
const ts = req.get('X-Slack-Request-Timestamp');
if (!ts || Math.abs(Date.now() / 1000 - Number(ts)) > 300) return false;
const expected = 'v0=' + crypto.createHmac('sha256', process.env.SLACK_SIGNING_SECRET)
.update(`v0:${ts}:${req.rawBody}`).digest('hex');
const given = req.get('X-Slack-Signature') ?? '';
return given.length === expected.length && crypto.timingSafeEqual(Buffer.from(given), Buffer.from(expected));
}
app.post('/slack/deploy', async (req, res) => {
if (!fromSlack(req)) return res.status(401).end();
const domain = req.body.text.trim();
const sites = await orch('/sites');
const site = sites.ok && sites.body.find((s) => s.domain === domain);
if (!site) return res.json({ response_type: 'ephemeral', text: `No site called ${domain}.` });
const deploy = await orch(`/sites/${site.id}/deploy`, { method: 'POST' });
const text = !deploy.ok
? `โ ${deploy.body.error ?? deploy.body.message}`
: deploy.body.queued
? `โณ ${domain}: queued behind the running deploy.`
: `๐ Deploying ${domain} (deployment #${deploy.body.deploymentId}) โ requested by <@${req.body.user_id}>.`;
res.json({ response_type: 'in_channel', text });
});
app.listen(3000);
The command only deploys sites the token's account can access. To limit it further, create the token on a developer account with access to just those sites.
๐ Daily health report
A short Python script that lists sites that are down, servers that are offline or have open alerts, and disks that are nearly full โ and posts it to Slack. It needs an admin token, because the fleet endpoints are admin-only.
#!/usr/bin/env python3
import os
import requests
API = os.environ["ORCH_URL"] + "/api"
HEADERS = {"Authorization": f"Bearer {os.environ['ORCH_TOKEN']}"}
def get(path):
res = requests.get(API + path, headers=HEADERS, timeout=30)
res.raise_for_status()
return res.json()
problems = []
for site in get("/uptime")["sites"]:
if site["monitoring"] and site["status"] == "down":
problems.append(f"๐ด {site['domain']} is down ({site['statusCode'] or 'no response'})")
for server in get("/fleet/servers")["servers"]:
if server["agentStatus"] == "offline":
problems.append(f"๐ด {server['name']}: agent offline")
if server["activeAlerts"]:
problems.append(f"๐จ {server['name']}: {server['activeAlerts']} open alert(s)")
metrics = (server.get("latest") or {}).get("m") or {}
for disk in metrics.get("disks", []):
if disk["total"] and disk["used"] / disk["total"] > 0.9:
problems.append(f"๐พ {server['name']} {disk['mount']}: {disk['used'] / disk['total']:.0%} full")
report = "\n".join(problems) or "โ
All sites up, all servers healthy."
print(report)
if os.environ.get("SLACK_WEBHOOK_URL"):
requests.post(os.environ["SLACK_WEBHOOK_URL"], json={"text": report}, timeout=10)
Run it daily from cron or a scheduled CI job. For instant alerts instead of a daily report, use the panel's own alerts and webhooks.