Back to changelog
New
•2 minute read

Atlas Scripts: Multi-Tenant Environments

atlas script exec, query, and loop now run on every target of an environment defined with for_each, such as a database or a schema per tenant, with each tenant's own URL and variables.

One script file serves the whole fleet. Tenants run in turn, and a failing tenant stops the run with a non-zero exit code.

Defining the Tenants

Define the tenants with for_each, exactly as for atlas migrate apply. Attributes such as tenant are bound to the scripts' variables, per tenant:

atlas.hcl
locals {
tenants = ["tenant_1", "tenant_2"]
}
env "prod" {
for_each = toset(local.tenants)
url = "sqlite://${each.value}.db"
tenant = each.value
script {
src = "file://scripts"
}
}

Each tenant prints its own report, so put the tenant in the script's output to tell them apart:

scripts/tenants.script.hcl
variable "tenant" {
type = string
}
script "query" "user_counts" {
query "counts" {
sql = "SELECT count(*) AS total, count(CASE WHEN plan = 'pro' THEN 1 END) AS pro FROM users"
rows {
total = int
pro = int
}
}
output {
message = "${var.tenant}: ${query.counts.rows[0].total} users, ${query.counts.rows[0].pro} on pro"
}
}

One Run per Tenant

A single command runs the script on every tenant in turn. Scripts pulled from the Atlas Registry are fetched once, so every tenant runs the same version.

$ atlas script query --env prod --run '^user_counts$' --quiet
tenant_1: 4 users, 2 on pro
tenant_2: 3 users, 1 on pro

Atlas Scripts are available to Atlas Pro users that purchased Atlas Pipelines; run atlas login to get started. See Running on every tenant in the Atlas Scripts documentation for the full behavior, including per-tenant variables and --format output.

featureatlas scriptsmulti-tenantatlas pro