How to automate tenant onboarding in Keycloak
Automated tenant onboarding in Keycloak means a script or pipeline creates the tenant structure, the identity links and the first administrator through code, so no one has to click through the admin console for each new customer. Teams need this when a SaaS or shared-platform team signs up customers every week, because each manual setup repeats the same steps and each repeat is a chance for a missed domain, a wrong redirect URI or an admin account given the wrong role. This section assumes you have already chose an organizations-based or realm-based tenant model, and the steps that follow depend on that choice.
Manual setup is cheap for the first few tenants and then becomes the bottleneck. It is easy to audit one click path, but hard to prove that every tenant received the same configuration. Realm-per-tenant models give strong isolation, but every new realm carries its own clients, flows, keys and administrative surface, so the work and the runtime cost grow with the count. Organizations inside one realm reduce that per-tenant overhead, but they move more of the tenant boundary into client logic and token handling. Automation through the Admin REST API or Terraform makes the onboarding steps repeatable and reviewable, and it lets you test the same change in a staging realm before production. Confirm the exact Admin REST API resources and Terraform provider attributes for your Keycloak version against the server administration guide, since fields and endpoints change between releases.
Before writing any code, decide who owns the onboarding service account, which roles it holds, and where its credentials are stored. The service account should hold only the permissions needed to create organizations, domains, identity providers and first users, and it should not be a master-realm administrator. Define a tenant record as the single input (name, domains, identity provider settings, first admin email), keep it in version control, and make the pipeline idempotent so a rerun does not duplicate members or providers. Plan offboarding as carefully as onboarding: disabling members, removing identity providers, revoking sessions and deleting client scopes should be scripted and logged, and the invitation flow should be tested end to end in a non-production environment that uses your own SMTP relay. Ask your team to confirm how the organization and invitation objects behave in your chosen Keycloak release before you commit to the design.
Admin REST API or Terraform: which path fits your team
The Admin REST API path puts onboarding logic in code that your platform service runs when a customer signs up or an operator requests a new tenant. The service creates the organization, links the domain, registers the identity provider, creates the first admin and sends the invitation, one call at a time. Keycloak itself is the system of record for the tenant at that point, so the service must read back what exists before it creates anything, or retries will produce duplicates.
- State ownership: The Keycloak database holds the authoritative configuration. Your service usually keeps a thin mapping from its own tenant ID to Keycloak organization and identity provider IDs, and that mapping becomes critical data to back up.
- Drift detection: There is no built-in comparison against a desired state. You need a scheduled reconciliation job that reads Keycloak and compares it with your records, or you accept that manual console edits go unnoticed.
- Secrets: Client secrets and identity provider secrets are returned to your code at creation time. Store them in a secrets manager at that moment, and confirm which fields the API returns again later, since some values are masked on read.
- Upgrade maintenance: Your code depends on endpoint paths and payload shapes. Each Keycloak minor release needs a test run against your onboarding flows, and your team owns every fix.
Confirm the exact endpoints and payloads against the Admin REST API reference for the Keycloak version you run, before writing the client.
The Terraform path describes tenants as declarative resources, such as realms, organizations, identity providers and clients, in version-controlled files. A pipeline runs a plan, a person or policy reviews it, and an apply makes Keycloak match the code. Terraform keeps its own state file that maps each resource to a Keycloak object, so the state file is part of your security boundary and must be stored and locked properly.
- State ownership: The state file, not Keycloak, records what Terraform manages. Use a remote backend with locking and access control, and decide who may run applies against production.
- Drift detection: A scheduled plan with no changes is a drift check. Any manual change in the console appears as a planned difference, which suits teams that want changes only through code.
- Secrets: Values such as client secrets end up in state, so the state store must be encrypted and restricted. Pull secrets from a secrets manager through variables rather than committing them to the repository.
- Upgrade maintenance: The Keycloak provider is a separate project with its own versions. Pin the provider version to the Keycloak release in use, and confirm that pairing before every Keycloak upgrade. Provider upgrades can also change resource behavior, so plan them as their own change.
Before adopting this path, confirm with the provider documentation which resources and attributes cover the tenant features you need, such as organizations and identity provider linking.
The choice rarely turns on technical capability alone. It turns on who triggers tenant creation, how often it happens and who must approve it. A hybrid is common: Terraform manages stable shared configuration such as realms, base clients and default settings, while a service handles per-customer onboarding events that arrive at unpredictable times.
- Trigger source: If customers self-serve signup through your product, a service call is the natural trigger. If operators create tenants in batches with approvals, a pipeline fits better.
- Review and audit: Pipelines give a reviewable diff for every change. Service calls need their own audit logging of who or what requested each action.
- Team skills: Consider whether your platform team already runs Terraform for other infrastructure. Consider whether your application team can own Java or Python client code that calls Keycloak.
- Failure handling: A service call must handle partial failures, such as an organization created but its identity provider not yet registered. A pipeline run can be re-applied to converge.
- Recurring cost: Both paths carry upgrade work each Keycloak release. Ask any implementation partner to estimate that recurring work against your chosen design in writing.
Set the split in a short decision record before building, so each tenant change has one clear owner.
Onboarding options and when each fits
This table compares four ways to create a tenant in Keycloak: manual console work, scripted Admin REST API calls, Terraform applied per tenant, and Kubernetes Operator custom resources. Read each row against your team's change control, audit needs and volume of new tenants. The main takeaway is that the approach you pick sets who can trigger onboarding, how failures show up, and how easily you can prove what changed.
| Approach | Who triggers it | Auditability | Failure handling | Best fit |
|---|---|---|---|---|
| Manual console work | An administrator in the Keycloak admin console | Limited to admin event logs and whatever the team records by hand | Errors surface immediately, but partial setup is easy to leave behind and hard to find later | A handful of tenants, pilots, or one-off corrections |
| Scripted Admin REST API calls from the signup flow | The product's signup or provisioning service, on a customer action | Good if the service logs each call and ties it to a customer record | Your code must handle retries and compensating steps for each call; partial tenants are a known risk | Self-service onboarding where the product already owns the tenant record |
| Terraform apply per tenant | A pipeline run, usually after a reviewed change to tenant definitions | Strong: versioned definitions, plan output and an apply history | Failed applies stop and report state, but state drift and provider version changes need active management | Teams that already run Terraform and want reviewed, repeatable tenant changes |
| Kubernetes Operator custom resources (KeycloakRealmImport, client resources) | A GitOps controller or an engineer applying manifests to the cluster | Strong for realms and clients stored in Git; confirm what the Operator covers for organizations before relying on it | The Operator reconciles resources and reports status; confirm how it handles deletion and renamed objects | Clusters running the Operator where realm and client configuration is already managed as code |
Set up a repeatable tenant onboarding pipeline
This sequence turns tenant creation into a scripted, auditable workflow in which each step produces a verifiable result, so a new customer or business unit can be provisioned the same way every time without manual changes in the admin console.
Create a least-privilege provisioning service account
Create a dedicated service account in the Keycloak realm that the onboarding pipeline uses, and grant it only the admin roles needed to create organizations, manage their domains, register identity providers and create users. Keep the credentials in your secrets manager and do not reuse a human administrator's account. The step is done when a test token obtained by the pipeline can perform each required action and is refused for actions outside its role set, such as changing realm-wide settings.
Define the tenant input schema
Write a schema that lists every value the pipeline needs for a tenant: organization name and alias, email domains to claim, whether the tenant brings its own identity provider and its connection settings, the first administrator's email address, and the branding or group defaults to apply. Validate submitted records against this schema before any API call is made, and reject incomplete or malformed domains. The step is done when an invalid test record fails validation with a clear error and makes no changes in Keycloak.
Create the organization and claim its domains
Call the Admin REST API to create the organization and attach the tenant's email domains to it. Domains must be verified before they can route users to the organization, so the pipeline should record the verification state it receives and stop short of enabling domain-based routing for unverified domains. Confirm the organization is listed with the expected domains, and confirm that a test address on an unclaimed domain is not routed to the organization. Check the exact Organizations behavior in the version you run, since the administration guide defines how domains are managed.
Register the tenant's identity provider when one is supplied
If the tenant brings its own identity provider, create the identity provider through the Admin REST API, link it to the organization and set the mapper settings the tenant requires. Store client secrets in the secrets store rather than in the tenant record, and confirm that the provider's redirect URI matches the value your Keycloak hostname produces. The step is done when a test sign-in through the provider completes and the user lands as a member of the correct organization. Tenants that use only local accounts skip this step, and the pipeline should record that choice explicitly.
Create the first administrator and send the invitation
Create the tenant's first administrator as a user in the organization, assign the tenant admin role or the delegated permissions your design specifies, and trigger the invitation email through the organization member flow. Keep the invitation link single-use and time-limited according to your realm policy. Confirm the email reached a test mailbox, that the administrator can complete sign-in and set up required credentials, and that the administrator sees only their own tenant's users in the console.
Write the tenant record to your system of record
After Keycloak reports success, write a tenant record to the system your organization treats as authoritative, such as a CRM, configuration repository or database. Include the organization ID, realm, domains, provider link, administrator identifier and the date of provisioning, and record the Keycloak object IDs the API returned. The step is done when the record can be used to find every Keycloak object created for the tenant, which later supports offboarding and audits.
Confirm the audit trail for each change
Check that the Keycloak admin events for the run show the service account performing each create action, and that the events are stored and forwarded to your log platform. Confirm the audit records identify the actor, the object and the time. If admin event logging is not enabled in your realm, enable it before the first production run and test that a deliberately failed call is also recorded. The step is done when an auditor could reconstruct the full tenant creation from logs and the system of record alone.
How a signup request flows into Keycloak through a provisioning service
The flow starts when a customer submits a signup form on the public side, and the form data goes to a provisioning service that you run inside your own infrastructure. That service either calls the Keycloak Admin REST API directly or runs Terraform against the same administration endpoints, and it creates the organization, its domains, the identity provider link and the first admin. Keycloak then sends the invitation through the SMTP server you configure. The admin hostname sits inside its own trust boundary, separate from the public frontend URL, so the provisioning service is the only path that reaches it. Check that every hand-off uses TLS and that the service account has only the roles it needs.
Signup data reaches Keycloak only through the provisioning service and its admin hostname.
Security controls for provisioning automation
A provisioning script can create realms, organizations, identity providers and administrators, so it carries more authority than most application service accounts. The controls below cover who holds that authority, where the API is reachable, how traffic is protected, what tenant input is trusted and how every change is recorded.
Scope the provisioning credential
The client or service account that creates tenants is a high-value secret. Give it only the realm and organization management roles the onboarding job needs, and avoid reusing the master realm admin account or a broad composite role. Store the client secret in your secrets manager, rotate it on a schedule you define, and confirm which roles the account holds in each realm it touches. Test the job with the narrowest role set first and widen only when a call fails.
Keycloak admin docsExpose the admin API on a private path
Keycloak's production guidance is to serve the admin console and Administration REST API on a different hostname or context path from public frontend URLs. Onboarding jobs should call that private endpoint from inside your network, not the public login host. Confirm with your reverse proxy that path restrictions block the admin paths from the internet, and check that the provisioning runner can reach the private endpoint and nothing else.
Production guideRequire TLS on every provisioning call
Provisioning requests carry client secrets, bearer tokens, tenant domains and initial administrator details. Keycloak's production guide calls for TLS on all communication, so every hop from the runner to the server and through the proxy should use HTTPS. Verify certificate chains in the automation client rather than disabling verification to get a job running, and include the proxy and any internal certificate authority in your review.
TLS guidanceValidate domains before trusting them
A domain on an organization record decides which users can be routed to that tenant's identity provider. Before the job links a domain, confirm that the requesting customer controls it, using a method your onboarding process defines such as a verification record or a reviewed approval. Reject free-mail providers and domains already claimed by another tenant. Treat tenant names, domains and administrator emails as untrusted input and validate them in the pipeline, not only in the form that submits them.
Record every provisioning action
Each create, update and delete made by the onboarding job should leave a trail showing who or what made the change, the target realm or organization, the time and the request outcome. Keep the job's own logs alongside Keycloak's admin events, and confirm that your retention matches your audit needs. Include a change record for each tenant so reviewers can trace an administrator account back to the approved onboarding request that created it.
Offboarding a tenant without leaving orphaned access
Offboarding a tenant is a sequence, and the order matters more than speed. Start by blocking sign-in for the organization before touching anything else, so no new sessions or tokens are issued for its members while you dismantle the rest. Then unlink or remove the tenant's identity providers and domains. Removing the domain first matters because a domain still attached to an organization can keep routing users from that customer's email space into a login path you are about to close. Once providers and domains are gone, remove members and their tenant-scoped roles and groups, and confirm that no client mapper or application still reads the organization claim for that tenant.
Users are where orphaned access usually hides. A person who belongs to two organizations, or who signed in once through a shared identity provider, must not lose access to the other tenant when you remove the first. Before deleting any account, list its organization memberships, its realm-level roles and any client roles granted through a tenant group. Remove only the tenant-specific memberships and assignments, and delete the user only when the account exists solely for that tenant and your contract says so. Also review active sessions and offline tokens for those users, because revoking membership does not by itself end a session that is already open.
Retention is a contract question, not a Keycloak default. Decide with the customer, and record in writing, whether user records, login events, admin audit entries and any tenant configuration are deleted, exported to the customer, or kept for a defined period. Ask your legal or compliance owner which retention rule applies to each category, and confirm how your logging backend and event store handle deletion requests. Then test the whole removal path in a non-production realm that mirrors your onboarding automation, including the Admin REST API calls or Terraform steps that reverse onboarding. Check that a removed user cannot sign in through any provider, that the domain no longer routes, and that another tenant's users are unaffected. Repeat the test after each Keycloak upgrade, since admin endpoints and event behavior can change between releases.
Limits to confirm before you automate
Automation is only as reliable as the Keycloak version, scale and delivery path underneath it. The four checks below cover what your scripts can call, how many realms and organizations your environment holds, whether invitation email will actually leave the server, and whether each tenant's identity provider needs manual trust before onboarding runs end to end.
Confirm endpoints in your exact version
Admin REST endpoints and Terraform provider resources change between releases, so a script written against one version can fail silently on another. The current release is 26.8.1, published October 13, 2026, but many production estates run older minor versions. Pin the Keycloak version in your environment, then test each call your onboarding flow makes (organization creation, domain assignment, identity provider linking, first admin invitation) against that exact version in a non-production realm. Check the Keycloak upgrade notes for every minor release between your version and the target before you change either the server or your scripts.
Keycloak upgrading guideMeasure realm and organization scale
Whether you create one realm per tenant or organizations inside one realm changes how your automation runs and how it performs. Each new realm adds configuration, caches and admin console load, and onboarding a large batch can slow the server for everyone. Ask your team to state the expected tenant count at year one and year three, the number of organizations per realm you plan to keep, and the number of administrators who will use the console. Load-test a batch of onboarding runs on the same database and cluster design you will use in production, since the high availability architecture you choose sets the limits.
Verify email delivery before invitations
Invitation emails for first admins and new members depend on the SMTP path working from the Keycloak nodes. Keycloak 26.8 enforces StartTLS for SMTP connections and does not fall back to plaintext, so a relay that worked under an older configuration can start rejecting connections after an upgrade. Confirm the relay host, port, authentication method and certificate chain with your mail team, send a test message from each node, and check that your onboarding script treats a failed send as a failed step rather than a completed tenant. Add a second check that the invitation link uses the correct public frontend hostname.
Plan manual trust for external providers
When a tenant brings its own Entra ID, Okta or SAML identity provider, the automation can create the provider record, but the customer's side still has to trust Keycloak. That usually means registering a redirect URI, exchanging metadata, or sharing a signing certificate, and that work sits with the customer's administrator. Decide which steps your script can complete and which need a human handoff, then build a verification step that performs a test sign-in before marking the tenant live. Also confirm how backchannel logout tokens from external providers are validated under the 26.8 rules, since signature validation is mandatory there.
Questions buyers ask about tenant onboarding automation
What drives the cost of automating tenant onboarding in Keycloak?
The main driver is the number of tenant objects the automation must create and keep in sync: organizations, verified domains, identity providers, mappers, first admin accounts, and invitation emails. Each additional identity provider type (for example OIDC, SAML, or a directory-backed provider) adds configuration variants, test cases and credentials handling. Pipeline work matters too, including how onboarding requests are submitted, approved and logged, and how failures are retried without creating duplicate objects. Test work is often underestimated, because every tenant path needs a repeatable test in a non-production Keycloak. Ongoing cost comes from upgrade maintenance, since Admin REST API details and Terraform provider resources can change between Keycloak releases. Ask any quote to split one-time build work from recurring upgrade and support work, and to list each tenant object in scope.
How long does tenant onboarding automation take to build?
Duration depends on the written scope, not on a general estimate. A narrow scope covering one tenant model, one identity provider type and manual domain verification takes less time than a scope that adds several provider types, self-service onboarding requests, offboarding workflows and a full test suite. Other timing factors include how quickly your team can confirm the admin model, how long domain verification takes for each customer, and how many environments the automation must run in. Before work starts, agree in writing on the deliverables, the environments covered, the acceptance tests and the handover steps. Ask for a timeline tied to those deliverables, with the assumptions that could move it listed separately.
What does our team need to provide before automation starts?
Most delays come from missing decisions rather than from technical work. Before build starts, you need to supply:
- An admin model: which internal teams may create tenants, who approves them, and which Keycloak roles or permissions the automation uses.
- A domain verification process: how a customer proves control of a domain, who checks it, and how the result is recorded.
- SMTP settings for invitation emails, with a sending domain your mail team controls and the test mailbox used during validation.
- Test tenants and test identity providers in a non-production Keycloak, including sample customer domains that can be safely created and deleted.
- Access to the systems that feed tenant data, such as a CRM or ticketing tool, if onboarding requests start there.
Ask the partner to confirm this list in writing as part of the scope.
Can our own team build tenant onboarding automation in Keycloak?
Yes, if your team has working knowledge of the Keycloak Admin REST API or the Terraform provider for Keycloak, plus experience with CI/CD pipelines and secrets handling. The work involves designing idempotent scripts, handling partial failures, testing against a real Keycloak, and reviewing changes before they reach production. A partner helps when the team lacks those skills, when the tenant model is still being decided, when several identity provider types must be supported at once, or when the automation has to pass a security or compliance review on a short schedule. Many teams split the work: the internal team owns the tenant data and approval flow, and an outside team builds and tests the Keycloak layer. Whichever route you take, the decision should rest on a skills check against the written scope.
What is the difference between automating tenant onboarding through the Admin REST API and through Terraform?
The Admin REST API gives direct, fine-grained control over realms, organizations, clients, identity providers and users, and suits onboarding services that run on demand when a tenant is created. Terraform manages the same objects declaratively, stores desired state in version control, and shows planned changes before they apply, which suits teams that want reviewable, repeatable tenant definitions. Many designs combine both: Terraform manages baseline configuration, while a small service calls the Admin REST API for tenant events that need immediate action, such as creating a first admin. Either path needs careful handling of state, because a tenant created outside the tracked state can drift. Confirm which Terraform provider and resource types cover the objects in your scope before choosing.
What does ongoing support cover after tenant onboarding automation goes live?
Ongoing support covers the work that keeps the automation correct as Keycloak and your tenant base change. This includes reviewing each Keycloak release for changes to the Admin REST API, Terraform resources or organization behavior, updating the automation and its tests, rerunning acceptance tests in a non-production environment, and supporting failed onboarding or offboarding runs. Recurring work also includes reviewing audit logs for onboarding actions and maintaining the runbook for domain verification and invitations. DeployOpen offers ongoing support, upgrades and continuous testing as retainers, and the scope of any retainer is agreed in writing. Ask for a list of included activities, response expectations in writing, and what changes would be billed as separate work.
How do we offboard a tenant cleanly without leaving orphaned accounts or providers?
Clean offboarding is a designed workflow, not a single delete call. The sequence normally disables sign-in for the tenant first, revokes active sessions, removes or unlinks identity providers and domains, and then handles member accounts according to your retention rules. Keep in mind that users may belong to more than one organization, and that shared identity providers or clients must not be removed while other tenants still use them. Record each step in an audit log so you can prove what was removed and when. Test offboarding in a non-production realm with the same identity provider types you run in production, and confirm the retention and deletion rules with your legal and privacy teams before build starts.
What security controls should tenant onboarding automation include?
The automation holds credentials that can create realms, organizations and identity providers, so access to it should be treated as administrative access. Store its client secret or service account credentials in a dedicated secrets store, grant it only the fine-grained roles its tasks require, and keep the Administration REST API on a hostname or context path separate from public frontend URLs, as the production guide recommends. Validate every input, including tenant names and domains, before it reaches Keycloak, and reject duplicate domains that could route one customer's sign-in to another tenant. Log each onboarding and offboarding action with the requester and approver. Confirm these controls against your own security policy and any framework your auditors test, and do not treat this list as an assessment result.
How DeployOpen scopes and delivers tenant onboarding automation
DeployOpen fixes the tenant model, the onboarding inputs and the offboarding rules in writing before any provisioning code is written. That scope settles whether tenants map to realms, organizations inside one realm, or another model, which attributes a tenant request must carry, who approves a new tenant, which identity providers and domains each tenant may use, and what happens to users, clients, groups and audit records when a tenant leaves. Each of those decisions changes the code, so agreeing them first keeps the build from being reworked later. The written scope also sets the deliverables, the acceptance checks and the handover items, and it is the document a quote is based on.
Once the scope is agreed, DeployOpen builds the provisioning path inside your own infrastructure, using the Admin REST API, Terraform or both, as the scope requires. The path runs under a service account with the narrowest roles that work, and the team checks it against a non-production realm that mirrors your production settings before anything touches production. Invitation emails, first-admin creation and the offboarding sequence are tested end to end, including failure cases such as a half-created tenant. Confirm with your own security team how the automation credentials will be stored, rotated and logged, because those decisions are part of the delivery, not an afterthought.
DeployOpen does not publish prices. A quote follows from the written scope, so the quote reflects the tenant model you choose, the number of identity providers and integrations in play, and whether offboarding must also remove data in connected systems. Keycloak's own upgrades change the Admin REST API and the Terraform provider surface over time, so many teams add a retainer for upgrades and continuous testing of the provisioning path. Ask for the retainer terms in writing and confirm which tests run after each Keycloak release before you sign.

