Build · Get started
Build a provisioning tool
A complete small application, from an empty folder to a tool you can run from a pipeline. Every line is tested.
What you will build
A command line tool, provision, that makes sure a project exists, asks Colossium for a database or a bucket in it, and waits until the request is done. You run it by hand or from a pipeline:
COLOSSIUM_API_TOKEN=... npx tsx provision.ts --project orders --kind databases.create --name orders-db --region euIt is small on purpose, and it does what a real integration must: it checks its token before acting, finds what already exists instead of making it twice, survives a dropped connection, waits for a human approval without timing out too soon, and never writes a secret to a log. You can run it twice with the same arguments and the second run will find the first request and follow it, not make another.
Both source files are in this page, and a test runs them against a stand-in for the API on every change to these docs. If the code here stops working, the build fails.
Before you start
- Node 20 or later (
node --version). - An organisation on Colossium, and an owner or administrator's account, to create a token.
- An empty folder. Nothing else: the code has no dependencies except
tsx, which runs TypeScript directly.
mkdir provisioning-tool && cd provisioning-tool
npm init -y
npm install --save-dev tsx typescriptStep by step
Make a token with the least it needs
In the console, open API access and create a token named provisioning-tool. Give it Make requests (resource.write) and Read resources and requests (resource.read), and Create projects (project.write) if the tool should create a project that does not exist. Nothing else: it does not need to delete or read the audit log.
If you already have the project, make the token limited to that project and leave out project.write. Then even a bug in your tool cannot touch anything else.
read -rs COLOSSIUM_API_TOKEN && export COLOSSIUM_API_TOKENKeep the token in the shell, a secrets manager or your pipeline's secret store. Never write it into the project folder.
Add the client
Save the reference client as colossium-client.ts next to your code. It is one file with no dependencies. It handles authentication, retries, pagination, idempotency and polling, so your tool can be about your job and not about HTTP.
Write the tool
Save this as provision.ts. Read the comments: each numbered step is one idea.
/**
* provision: a small command line tool that makes sure a project exists, asks Colossium for a database or a bucket in it, and waits
* until the request is done. It is the application built in the "Build a provisioning tool" guide. Run it from a pipeline or by hand:
*
* COLOSSIUM_API_TOKEN=... npx tsx provision.ts --project orders --kind databases.create --name orders-db --region eu
*
* Running it twice with the same arguments is safe: the idempotency key is built from them, so the second run finds the first
* request instead of making another.
*/
import { Colossium, ColossiumError, type ServiceRequest } from './colossium-client'
export type ProvisionArgs = {
project: string
kind: 'databases.create' | 'storage.create'
name: string
region: 'eu' | 'us'
timeoutMs?: number
}
export class UsageError extends Error {}
export function parseArgs(argv: string[]): ProvisionArgs {
const get = (flag: string) => { const i = argv.indexOf(flag); return i >= 0 ? argv[i + 1] : undefined }
const project = get('--project'), kind = get('--kind'), name = get('--name'), region = get('--region') ?? 'eu'
if (!project || !/^[a-z0-9]+(-[a-z0-9]+)*$/.test(project)) throw new UsageError('--project must be a project slug such as orders.')
if (kind !== 'databases.create' && kind !== 'storage.create') throw new UsageError('--kind must be databases.create or storage.create.')
if (!name || !/^[a-z]([a-z0-9-]{0,27}[a-z0-9])?$/.test(name)) throw new UsageError('--name must use lower-case letters, numbers and hyphens, starting with a letter, up to 29 characters.')
if (region !== 'eu' && region !== 'us') throw new UsageError('--region must be eu or us.')
const timeout = get('--timeout-minutes')
return { project, kind, name, region, timeoutMs: timeout ? Number(timeout) * 60_000 : undefined }
}
/** Finds the project by its slug, or makes it. Needs project.write only when the project does not exist yet. */
async function ensureProject(client: Colossium, slug: string, log: (m: string) => void): Promise<string> {
for await (const p of client.projects.iterate()) if (p.slug === slug) { log(`Using project "${p.name}".`); return p.id }
log(`Creating project "${slug}".`)
return (await client.projects.create({ name: slug, slug })).id
}
export async function provision(client: Colossium, args: ProvisionArgs, log: (m: string) => void = console.log): Promise<ServiceRequest> {
// 1. Check the token before doing anything. Stop early, with a clear message, if it cannot do the job.
const me = await client.verify()
if (!me.scopes.includes('resource.write')) throw new UsageError('This token needs the resource.write permission to make requests.')
log(`Token "${me.name}" is valid for organisation ${me.organisation_id}.`)
// 2. Find or make the project. A token limited to some projects can only use those, and cannot make new ones.
const projectId = await ensureProject(client, args.project, log)
// 3. Ask for the service. The key identifies this intent, so a rerun cannot make a second request.
const key = `provision-${args.project}-${args.kind}-${args.name}`
const { request, replayed } = await client.requests.create({ kind: args.kind, project_id: projectId, input: { name: args.name, region: args.region } }, key)
log(replayed ? `A request for this already exists (${request.id}). Following it.` : `Request ${request.id} accepted. It waits for approval.`)
// 4. Wait for it. Approval is a person's decision, so this can take a while.
const done = await client.requests.waitFor(request.id, { timeoutMs: args.timeoutMs, onUpdate: (r) => log(` state: ${r.state.replace(/_/g, ' ')}`) })
if (done.state === 'failed') throw new Error(`The request failed: ${done.failure ?? 'no reason was given'}.`)
if (done.state === 'cancelled') throw new Error('The request was cancelled.')
log(`Done. Resource ${done.resource_id ?? '(see the console)'} is ready.`)
return done
}
/** The command line entry point. Returns the exit code. */
export async function main(argv: string[], log: (m: string) => void = console.log, client?: Colossium): Promise<number> {
try {
await provision(client ?? new Colossium(), parseArgs(argv), log)
return 0
} catch (e) {
if (e instanceof UsageError) { log(e.message); return 2 }
// Log the code and the request id, which support can look up. Never log the token or the request headers.
if (e instanceof ColossiumError) { log(`${e.code} (${e.status}): ${e.message}${e.requestId ? ` [request id ${e.requestId}]` : ''}${e.docUrl ? `\n ${e.docUrl}` : ''}`); return 1 }
log(e instanceof Error ? e.message : 'Something went wrong.')
return 1
}
}
Run it
npx tsx provision.ts --project orders --kind databases.create --name orders-db --region euYou should see something like this. The pause on "awaiting approval" is a person deciding:
Token "provisioning-tool" is valid for organisation 7a1c4e92-0b3d-4f58-8a26-5e9d1c7b3f04.
Creating project "orders".
Request c58a1f34-7e2b-4d60-9a8c-3b1e4f70d625 accepted. It waits for approval.
state: awaiting approval
state: running
state: succeeded
Done. Resource 9b6e2d70-1c84-4a95-8f3e-6d0a5b17c2e9 is ready.Run it again
Run the same command. It finds the project and the existing request, and follows it without making a second one:
Using project "orders".
A request for this already exists (c58a1f34-...). Following it.
state: succeeded
Done. Resource 9b6e2d70-... is ready.That is idempotency at work, and it is why the tool is safe to put in a pipeline that might be retried.
Why it is built this way
| Choice | Reason |
|---|---|
It calls verify() first | To stop early, with a clear message, if the token cannot do the job, before changing anything. |
| The idempotency key is built from the arguments | So a rerun, a retry and a second pipeline run all mean the same intent, and none makes a second resource. |
| It waits up to 15 minutes by default | Approval is a person's decision. A short timeout would report a healthy request as broken. |
--timeout-minutes is available | A pipeline should not wait forever. Give it a limit that fits the job. |
| Exit codes are 0, 1 and 2 | 0 done, 1 the API or the request failed, 2 you used it wrongly. A pipeline can tell them apart. |
| It logs the error code and request id, never the token | So a failure can be investigated with support, and a log is never a leak. |
Make it production-ready
- Add a project-limited token and an address limit if the tool runs from a server with a fixed address.
- Set an expiry on the token and put a reminder to roll it.
- Run it from a pipeline that has the token as a secret, not a visible variable. CI/CD shows how.
- Test your own changes against a stand-in for the API, as in Testing your integration.
- Read Data protection for builders and check the names you give things.
Names such as orders-db are visible to everyone in the organisation and are recorded in the audit log and in the request. Name things after what they are, never after a person or a customer.
Where next
- Add
storage.createand the other kinds. - Read every request in a project with
client.requests.iterate({ project_id })and report the ones that failed. - Use
client.auditEvents.iterate({ action: "api_token.create" })to watch for tokens being created.
This page as MarkdownReport a problem with this pageOlympus Group Holdings, Inc.