Deploy from CI with an API token
Make an API token that can only read one environment, and a CI job that waits until a commit is running there and healthy, with a complete script.
The situation
In Wardn a push is the deploy: when a commit lands on a tracked branch, Wardn renders it and applies it (Connect a source). CI does not have to deploy anything. What it usually lacks is an answer: did the commit I just merged reach staging, and is it healthy? You want the pipeline to go green only then, and red with a reason if the apply failed.
That job needs to read, and nothing else. So the token it carries is the narrowest one that works: deployment:read on one environment. A leaked copy can look at that environment's deployments and can neither sync, restore nor change anything, and it cannot see any other environment (API tokens).
Repository layout
The example uses GitHub Actions. The script is plain bash, curl and jq, so it runs unchanged in any CI system.
Settings
The token
A token has access rows, each a list of permissions on a list of places. You make the token in the web app, because the web app makes the secret and shows it once; the API can create the token record but returns no secret.
Open Settings › API Tokens and choose New token. Only Owners and Admins can (API tokens).
Under Details, set Name to payments-api CI, staging and a description such as "Waits for a commit to be healthy in staging". Set Expires to 90 days.
Under Access, choose Add access. In Where, pick the staging environment (not Organization). In Can, tick deployment:read and nothing else. Choose Add access in the dialog.
Under Limits, set a Rate limit of 120 requests per minute. The script makes one call per deployment every ten seconds, plus one to list them.
Choose Create token, and copy the secret from Copy your token now. It begins with wrd_, is stored only as a hash and is not shown again.
Place the token and the two values the job needs in your CI system's secret store. In GitHub: the secret WARDN_TOKEN, and the variables WARDN_API_URL (https://wardn.example.com) and WARDN_ENVIRONMENT_ID (the environment's id, from its page or GET /environments).
| Row | Value | Why |
|---|---|---|
| Place | The staging environment | A place includes everything inside it: the deployments placed on the environment or on its clusters, and clusters added later. |
| Permission | deployment:read | Reads the deployment list and each deployment's state, which carries the running commit, sync and health. |
| Not included | deployment:sync, deployment:rollback, snapshot:read, token:manage | The job never writes. Add snapshot:read only if you want it to read snapshots too. A token can never hold token:manage. |
The token also can never do more than the person who made it. If that person leaves or loses access to staging, the token stops working there within seconds.
The script
It lists the deployments of the environment, reads each one's state, and finishes when every one runs the commit, has synced and is healthy. It stops with an error if the apply of that commit failed.
#!/usr/bin/env bash
# Wait until every deployment in one environment runs a commit and is healthy.
#
# Needs: WARDN_API_URL, WARDN_TOKEN, ENVIRONMENT_ID, COMMIT (a full or abbreviated commit id).
# Optional: NAME_FILTER (only deployments whose name contains it), TIMEOUT and INTERVAL in seconds.
# Exit codes: 0 ready, 1 an apply failed, 2 nothing to watch, 3 timed out.
set -euo pipefail
: "${WARDN_API_URL:?set WARDN_API_URL}"
: "${WARDN_TOKEN:?set WARDN_TOKEN}"
: "${ENVIRONMENT_ID:?set ENVIRONMENT_ID}"
: "${COMMIT:?set COMMIT}"
NAME_FILTER="${NAME_FILTER:-}"
TIMEOUT="${TIMEOUT:-900}"
INTERVAL="${INTERVAL:-10}"
# --retry also retries a 429, and waits as long as Retry-After says.
api() {
curl -fsS --retry 5 --max-time 30 -H "Authorization: Bearer $WARDN_TOKEN" "$@"
}
# One line per deployment in the environment: "<id><TAB><name>". Previews are left out.
deployments() {
local cursor="" page
while :; do
local args=(-G "$WARDN_API_URL/api/v1/deployments"
--data-urlencode "environmentId=$ENVIRONMENT_ID"
--data-urlencode "preview=exclude"
--data-urlencode "limit=200")
if [ -n "$NAME_FILTER" ]; then args+=(--data-urlencode "q=$NAME_FILTER"); fi
if [ -n "$cursor" ]; then args+=(--data-urlencode "cursor=$cursor"); fi
page=$(api "${args[@]}")
printf '%s' "$page" | jq -r '.items[] | "\(.id)\t\(.name)"'
cursor=$(printf '%s' "$page" | jq -r '.nextCursor // empty')
if [ -z "$cursor" ]; then break; fi
done
}
# Reads one deployment state on stdin and prints: ready, failed:<why> or waiting:<why>.
verdict() {
jq -r --arg c "$COMMIT" '
def at_commit(p):
p != null and (((p.commit // "") | startswith($c))
or any(p.apps[]?; (.commit // "") | startswith($c)));
if .sync == "failed" and at_commit(.desiredProvenance) then
"failed:the apply failed: \(.syncMessage)"
elif .sync == "synced" and at_commit(.provenance) then
if .health == "healthy" then "ready"
else "waiting:at the commit, health is \(.health) \(.healthMessage)" end
else
"waiting:not at the commit yet, sync is \(.sync)"
end'
}
deadline=$(( $(date +%s) + TIMEOUT ))
while :; do
list=$(deployments)
if [ -z "$list" ]; then
echo "No deployments found in environment $ENVIRONMENT_ID. Is the token's access on it?" >&2
exit 2
fi
waiting=0
failed=0
total=0
while IFS=$'\t' read -r id name; do
total=$((total + 1))
result=$(api "$WARDN_API_URL/api/v1/deployments/$id/state" | verdict)
case "$result" in
ready) ;;
failed:*) echo "FAILED $name: ${result#failed:}"; failed=$((failed + 1)) ;;
*) echo "waiting $name: ${result#waiting:}"; waiting=$((waiting + 1)) ;;
esac
done <<<"$list"
if [ "$failed" -gt 0 ]; then exit 1; fi
if [ "$waiting" -eq 0 ]; then
echo "All $total deployments run ${COMMIT:0:7} and are healthy."
exit 0
fi
if [ "$(date +%s)" -ge "$deadline" ]; then
echo "Timed out after ${TIMEOUT}s with $waiting of $total deployments not ready." >&2
exit 3
fi
sleep "$INTERVAL"
doneHow it decides, from the fields of GET /deployments/{id}/state:
| State of the deployment | The script says |
|---|---|
sync is synced and the running snapshot's commit is yours (provenance) and health is healthy | ready |
the same, but health is progressing, degraded or unknown | waiting, with healthMessage. A rollout in progress is normal, so it waits for the timeout rather than failing at once. |
sync is failed and the snapshot Wardn wants (desiredProvenance) is your commit | failed, with syncMessage |
anything else, such as out_of_sync or applying, or a different commit | waiting |
A deployment on an environment reports one state for all its clusters: synced once every cluster has applied the snapshot, and the worst health among them. A deployment with several apps counts if any app of the snapshot is at your commit.
The workflow
name: wait-for-wardn
on:
push:
branches: [main]
jobs:
staging:
runs-on: ubuntu-latest
timeout-minutes: 20
steps:
- uses: actions/checkout@v4
- name: Wait for the commit to be healthy in staging
env:
WARDN_API_URL: ${{ vars.WARDN_API_URL }}
WARDN_TOKEN: ${{ secrets.WARDN_TOKEN }}
ENVIRONMENT_ID: ${{ vars.WARDN_ENVIRONMENT_ID }}
NAME_FILTER: payments-api
COMMIT: ${{ github.sha }}
run: ./ci/wait-for-wardn.shNAME_FILTER keeps the job to this app's deployments. Without it the job waits for every deployment in the environment, including ones that track another repository and will never show this commit. The job starts at the same time as Wardn's own work, so the first polls say "not at the commit yet"; that is the wait, not a problem. A newer commit that lands before yours is applied can keep this job waiting until the timeout, because the running commit is then no longer yours; set a concurrency group on the workflow if you want only the latest commit's job to continue.
Check that it worked
Check the token before you rely on it. wardn can-i reads the same WARDN_API_URL and WARDN_TOKEN:
export WARDN_API_URL=https://wardn.example.com WARDN_TOKEN=wrd_...
wardn can-i deployment:read --scope environment --on "$ENVIRONMENT_ID" # yes
wardn can-i deployment:sync --scope environment --on "$ENVIRONMENT_ID" # no
wardn can-i deployment:read # no: not on the whole organizationThen run the script by hand against a commit that is already running:
COMMIT=$(git rev-parse HEAD) ENVIRONMENT_ID=... NAME_FILTER=payments-api ./ci/wait-for-wardn.sh
echo $? # 0Push a real change and watch the job in CI go from waiting to the ready line. To see it fail, push a change that cannot apply, such as a Deployment with a bad field: the line begins FAILED and the exit code is 1. To see it time out, set TIMEOUT=30 while a deployment is held or a guardrail holds the commit; the commit never becomes the running snapshot, and the exit code is 3. Open the deployment's Snapshots tab to see why.
Then look at the token's own record. In Settings › API Tokens, open the token: Usage counts the calls, and Recent calls lists each one, allowed or not. A denied call is how you find a permission the job lacks; a run of them from a place you do not recognise is a leak.
api() { curl -fsS -H "Authorization: Bearer $WARDN_TOKEN" -H 'Content-Type: application/json' "$@"; }
# With an Owner's or Admin's token, not this one: a token cannot read tokens.
api "$WARDN_API_URL/api/v1/api-tokens/$TOKEN_ID/calls?outcome=denied"Rotate it
Rotate secret on the token's page makes a new secret and keeps the old one working for 24 hours, so you can update WARDN_TOKEN without a failed run. Only the token's owner can rotate it. Put a reminder before the expiry you chose, because an expired token cannot be rotated. If the secret leaks, Revoke token stops every secret at once.
If you also want CI to ask Wardn to apply again, for instance after changing a setting, give a second token deployment:sync on the same environment. Keep the waiting job's token read-only, so the credential that sits in every pipeline run cannot change anything.
Next
API tokens
Access rows, limits, usage, rotation and revocation.
API
Base URL, paging, retries and errors, for scripts of your own.
Read-only access for an on-call team
The same least-privilege idea, for people instead of a job.
Related: Permissions, Connect a source, Environments.
External Secrets Operator with Wardn
Let External Secrets Operator create the Secret from your secret store, keep the values out of git and out of Wardn, and still see in Wardn when a secret is missing, stale or has changed.
Read-only access for an on-call team
Let a team see production, its snapshots and its drift, with a custom role granted on the production environment, and change nothing.