When teams automate Keycloak administration through the Admin REST API
Teams automate Keycloak administration when realm, client and role changes made by hand in the admin console can no longer be reviewed, repeated or traced across development, test and production. The Admin REST API lets a script create and update users, clients, roles and groups over HTTPS, and kcadm.sh wraps the same API in a command-line tool that operators can run from a terminal or pipeline. Both act on the same objects the console shows, so the question is less about capability and more about whether a change should be written down, reviewed and replayed.
Automation is worth the effort when the same configuration must exist in several environments, when changes need a review trail, or when provisioning for onboarding or client registration happens too often to handle by hand. A scripted change can be version-controlled, tested against a non-production realm and rerun after a rebuild. Before committing to it, confirm who owns the scripts, where their credentials live and how a failed run is detected, since a half-applied change is harder to untangle than a console edit. Also confirm how your team will track the Keycloak release line, because API details can shift between versions.
Automation does not replace the admin console for one-off recovery work, such as regaining access when an administrator is locked out or inspecting a session that looks wrong during an incident. Those tasks are better handled by a named person with documented steps, and the resulting change should then be captured in code so the next deployment does not undo it. Keep a small set of break-glass administrator accounts outside the automation path, and test the recovery procedure before you need it.
Choosing how automation authenticates to Keycloak
Interactive login means a person authenticates to Keycloak as an administrator, typically with kcadm.sh config credentials using a username and password, and kcadm stores a session token locally for later commands. It suits one-off changes an operator runs at a terminal and reviews as they go. It does not suit unattended scripts, because the credential belongs to a named human, the session depends on that account's password and multi-factor state, and the script breaks the moment that person changes roles or leaves.
- Account ownership: the token carries the identity of a person, so audit events point to that individual rather than to a job.
- Credential storage: the password or token is cached on the machine running kcadm, which needs strict file permissions and cleanup.
- Multi-factor conflicts: if the admin account requires a second factor, unattended runs cannot complete the login.
- Lifecycle coupling: offboarding or a password reset silently disables every script that depends on that account.
- Scope: a human admin usually holds broad realm rights, far more than any single automation task needs.
Before relying on this method, confirm with your security team which admin accounts are permitted to hold local terminal sessions and where kcadm session files are stored on your hosts.
A dedicated confidential client gives automation its own identity. With service accounts enabled, the client authenticates with the client credentials grant and receives a token tied to a service account user that you can grant only the roles the job needs. The client can authenticate with a client secret or with a signed JWT (client assertion) so that no shared secret has to be stored in the script. This is the method most teams should use for recurring administration.
- Dedicated identity: create one client per automation job, not one shared client for everything, so revocation stays narrow.
- Secret authentication: the secret is stored in your secrets manager and rotated by generating a new value, updating consumers, then retiring the old one.
- Signed JWT authentication: the private key stays with the job, and rotation means publishing a new public key and cutting over, which avoids a shared bearer-style secret.
- Least-privilege roles: assign the service account only the client roles such as user or client management that the task requires.
- Token lifetime: tokens are short-lived, so a leaked access token expires quickly, but the client secret or private key remains the real long-term risk.
When you review this design, confirm which authentication option your Keycloak version supports for the client, and document an owner, a rotation schedule and the exact roles granted for each automation client.
Admin client libraries wrap the Admin REST API in a language-specific client and accept the same credentials as the service account method. They fit applications and pipelines that already run in code, such as provisioning jobs written in Java, Python, Go or JavaScript. The library does not change who authenticates, so the same least-privilege and rotation rules apply, but it moves the credential into application configuration, which changes where leaks happen.
- Credential source: load the client secret or signing key from a secrets manager or workload identity at runtime, never from source control or image layers.
- Token handling: use the library's built-in token refresh rather than writing custom token caching that may outlive its validity.
- Version pinning: library releases track Keycloak API changes, so pin the library version to the Keycloak release you run and test upgrades together.
- Separation of duties: run separate clients for read-only reporting and for write operations so a reporting job cannot create users.
- Error handling: treat authorization failures as a signal to stop, not as a reason to fall back to a human credential.
Confirm with the library maintainers that it supports the authentication method you chose, and check the library's documentation against the Admin REST API reference for your Keycloak version.
Automation methods and when each fits
This table compares kcadm, direct Admin REST API calls, admin client libraries, and Terraform or realm import on team skill, auditability, and drift risk. Read each row as a question to answer for your own team before choosing a method. The Terraform and realm import choices are covered in more depth on sibling pages.
| Method | Team skill needed | Auditability | Drift risk |
|---|---|---|---|
| kcadm (Keycloak admin CLI) | Shell scripting and familiarity with the Keycloak admin CLI commands | Commands are easy to store in version control, but the script itself must log who ran it and when | Medium: ad hoc runs can change live realms outside any recorded source of truth |
| Direct Admin REST API calls | HTTP, JSON, and OAuth 2.0 token handling for service accounts | Good if each request is logged at the gateway or in the calling pipeline, weaker if calls come from many scripts | Medium to high: each script encodes its own assumptions about current state |
| Admin client libraries | Language-specific SDK skills and dependency management in your application stack | Calls sit inside application code, so reviews and tests can cover them like other code | Medium: drift depends on whether the code is run on a schedule and compared with live state |
| Terraform provider | Infrastructure-as-code practice, state management, and provider version pinning | Plans and state history give a reviewable record of intended changes (covered on the Terraform sibling page) | Low when state is kept current, but state drift can still occur if people edit the console |
| Realm import and export | Knowledge of realm JSON structure and the export process | Exports are snapshots, so changes between exports are not visible in the file itself (covered on the realm import sibling page) | High if imports overwrite a running realm or secrets are handled inconsistently |
| Admin console changes | Console knowledge only | Weakest: changes are rarely logged outside the server's admin event settings | High: manual edits are the most common cause of configuration drift |
Scoping admin roles so scripts can do only their job
Automation accounts are often granted broad rights because narrow roles take longer to work out. The cards below cover where that breadth comes from in Keycloak and how to split it so each script holds only the permissions its job needs.
Map roles through realm-management
A service account gets administration rights through client roles on the realm-management client inside the target realm, such as manage-users or view-clients. Assign only the roles a script calls, and record which role each endpoint needs. Confirm the exact role names against the admin REST documentation for your Keycloak version before you write the mapping, because a wrong name either blocks the job or silently grants more than intended.
Split automation into one client per domain
Use separate clients for user provisioning, client registration and role management instead of one client that does everything. If the provisioning credential leaks, the attacker can only change users, not register new clients that could later obtain tokens. Each client gets its own secret, its own role mapping and its own log trail, which makes revocation and review simpler.
Keep the master realm out of routine jobs
Admin rights in the master realm reach every realm on the server, so a script that only manages one customer realm should not authenticate there. Create the service account in the realm it administers and reserve master for break-glass operators. Check that no existing automation still points at master credentials after you migrate.
Limit who can change the automation
Anyone who can edit the script repository or the CI variables that hold a client secret effectively holds the role. Store the secret in a managed secret store, restrict write access to the pipeline, and require review for changes to role mappings. Ask your platform team which secret store and approval workflow the organization already uses, so the controls fit existing practice.
Test each role against a non-production realm
Run every automation job against a test realm with the scoped service account before promoting it. A failed call that returns a permission error shows a missing role, and a job that succeeds with fewer roles than assumed shows the mapping works. Keep the test results with the role mapping so a reviewer can see why each role was granted.
How to set up a scripted admin client with checks
This sequence creates a dedicated automation client with a service account, grants it only the roles its scripts need, and proves each permission with a read call and a write call in a test realm. Each step ends with a check so you know the access is scoped correctly before any script touches production.
Choose the realm and scope for the admin client
Decide whether the automation client lives in the master realm or in a dedicated administration realm, and write down which realms the scripts must manage. The platform team owns this decision, with the security team reviewing it. Keep the master realm for bootstrap administration where possible, and create a separate realm for routine automation so its clients and roles stay isolated from the realms your users sign in to. Done when you have a written list of target realms and a named owner for the client. Confirm the approach against the Keycloak server administration guide for your Keycloak version before you create anything.
Create the client with service account enabled
In the admin console, or through kcadm in a session you already control, create a confidential client for the automation. Turn on client authentication and enable the service account, which lets the client obtain tokens with the client credentials grant and no human login. Store the generated client secret in your secrets manager, not in the script or the repository. Check that the client shows a service account user in the realm's user list, and that the client authentication setting is on. If the service account user does not appear, the client is not ready for scripted use.
Assign only the client roles the job needs
Open the service account user and assign the specific client roles from the realm-management client that match the work, such as view-users for a read-only report or manage-users for a provisioning job. Avoid assigning realm-admin or the full administrator role, because it grants every administrative capability in the realm. Write the chosen role names in the change record next to the script they serve. The check is a list of roles on the service account user that matches that record exactly, with no inherited composite role you did not intend to grant.
Authenticate and inspect the granted roles in the token
Request a token from the realm's token endpoint using the client credentials grant, either with kcadm config credentials or a direct POST from curl. Decode the access token payload and read the resource_access claim for the realm-management client. The roles listed there should match the roles you assigned in the previous step. Confirm that the token expiry is short and that no unexpected roles appear through composites. If the token lists roles you did not grant, stop and fix the role mappings before continuing. Use a decoder that runs locally so the token is not pasted into a public tool.
Run a read-only call to verify access
Using the token or kcadm session, make a read-only request such as listing users in the test realm or fetching the client list. Use a small page size so the output is easy to review. The call should succeed with the status the API documents for that endpoint. Then run the same read against a realm the client should not see and confirm it is refused with a forbidden response. This two-sided check proves the scope works in both directions. Record the request, the status codes and the realm names in your change log so the verification can be repeated after any role change.
Make a write call in a test realm
Create a disposable test user in the test realm through the Admin REST API or kcadm, using the same service account. Set a required attribute or add the user to a test group so you can confirm the write took effect. Then read the user back and confirm the attribute or group membership matches what you sent. Finally delete the test user and confirm it no longer appears in the listing. Run this write only in the test realm, never in production, because a write check that succeeds in the wrong realm means the scope is too broad. Keep the script output as evidence for your access review.
Record the verified configuration and set a review point
Save the client ID, the assigned role names, the realms it can reach and the results of the read, refused read and write checks in a versioned file or ticket. Name an owner who reviews the role mappings on a schedule your organization sets, and repeat the read and write checks after any Keycloak upgrade, because role names and admin behavior can change between releases. Confirm the secret rotation process is documented. When the record matches the live client and the checks still pass, the admin client is ready for production scripts.
What the kcreg default provider deprecation means for existing scripts
Scripts that register clients through the kcreg-based default client registration provider should be moved to the Admin REST API or kcadm before they break. The deprecation is a planning item for any team whose automation creates or updates clients with that tool, because a script that works today can stop working after an upgrade without any change on your side. Start by inventorying every pipeline, cron job, Ansible role or onboarding script that calls kcreg, and record the Keycloak version each one runs against.
Do not rely on a version number from memory or a blog post. Open the upgrade notes for the exact Keycloak release you run and for every release you plan to reach, and confirm the deprecation status and the removal timing stated there. The Keycloak upgrading guide is the first place to check. Record the status in your change ticket so the decision is traceable. Also confirm with your vendor or Red Hat support if you run the Red Hat build, since the supported timeline for that distribution may differ from the community release notes.
When you rewrite these scripts, map each kcreg call to an equivalent operation in kcadm or the Admin REST API, then test it against a non-production realm. Use a dedicated service account with a narrowly scoped admin role for the automation, rather than reusing an administrator credential, and confirm that the role grants only the client and realm-management permissions the script needs. Keep the original script in version control until the replacement has run through a full promotion cycle, so a rollback path exists if an edge case surfaces.
Security and operational considerations for admin automation
Scripts that create users, clients and roles hold more power than most day-to-day logins, so each control below limits what a script can reach, what it leaves behind and who approves changes. Together they decide whether automation makes Keycloak administration safer or simply faster to misconfigure.
Client credential storage and rotation
The service account secret used by kcadm or an admin client is a standing admin credential. Keep it in a secrets manager outside the repository, inject it at run time, and scope it to a dedicated client in a dedicated admin realm. Plan a rotation schedule and confirm that your scripts can read a new secret without a code change, so rotation does not become a reason to skip it.
Separate admin hostname and path
Keycloak's production guidance calls for exposing the admin console and Administration REST API on a different hostname or context path from public frontend URLs. Point automation at that admin endpoint only, and confirm that your reverse proxy blocks it from the public internet. Scripts that reach the admin API through a public route are a common way for admin access to leak outside the network you intended.
Keycloak production guideLeast-privilege admin roles
Give each script's service account only the realm-management roles its task needs, such as managing users in one realm, and never the master realm admin role by default. Review the role mapping whenever a script's scope changes. A user-provisioning job that can also edit clients or realm keys is a larger risk than its purpose justifies.
Audit logging of admin events
Automated changes look the same as manual ones unless you record them. Enable Keycloak admin event logging, decide how long events are kept, and forward them to your log platform. Tag each change with the service account and a job identifier where your tooling allows, so that an unexpected client or role change can be traced back to a specific script run.
Idempotent scripts
Scripts that run on a schedule or retry after a failure must not create duplicates. Look up each user, client or role by its stable key (username, clientId, role name) before creating it, and update instead when it exists. Test the script by running it twice against a non-production realm and confirm that the second run makes no changes, since duplicate clients with similar names are hard to spot later.
Version-controlled pipelines with review
Store admin scripts and their configuration in version control, run them from a pipeline with a protected branch, and require a second reviewer for changes that touch admin roles, client redirect URIs or identity providers. Keep pipeline runner credentials separate from the Keycloak secret where possible. The review step is the control that catches an over-broad script before it runs against production.
Questions buyers ask about Keycloak admin automation
What drives the effort and cost of scripting Keycloak admin tasks?
The main drivers are scope, the number of realms and clients, how many existing scripts or manual procedures must be replaced, and how much testing and review the automation needs before it touches production. A script that creates one client in one realm is a small job. Automating user lifecycle, role assignment and client registration across several realms, with idempotent runs and an audit trail, is a much larger one. Ask any partner to price these items separately: discovery of current admin practices, the automation build, test realm runs, security review of the service account, and handover documentation. Cost recurs mainly when the automation must follow Keycloak release changes, which the project ships on a fixed minor release cadence.
What does the client team need to provide for this work?
The work needs named identity owners who can decide which administrative actions the automation may perform, a test realm that mirrors production closely enough to validate changes, and access to the pipeline or runner where the scripts will execute. Identity owners also approve the role model for the service account, because that decision determines what the automation can change. Ask the partner to list exactly which accounts, secrets stores, network paths and approval steps they need before the build starts. Missing test realms are the most common reason automation work slows down, because changes then get validated against production data or not validated at all.
Can an internal team automate Keycloak administration without outside help?
Yes, a team with Keycloak and scripting experience can build this work internally, provided it can dedicate time to the build, testing and review. The harder parts are usually not the API calls themselves. They are designing a least-privilege service account, handling secrets, making scripts safe to rerun, and keeping them working through upgrades. Internal teams often underestimate the review step, where someone other than the author checks that the automation cannot grant broader access than intended. An outside partner adds value when the team lacks security review capacity or needs the work written down for auditors. Either way, confirm who will maintain the scripts after handover.
How long does Keycloak admin automation take, and what changes the timeline?
Duration depends on scope and on how quickly decisions are made, not on a fixed rule. The timeline usually grows with the number of realms, the number of administrative tasks being automated, the state of existing scripts, and whether identity owners agree on the role model early. Delays often come from waiting for a test realm, approving the service account permissions, or resolving how secrets are stored. A partner should give a timeline only in a written scope that lists deliverables and dependencies. Ask for the assumptions behind any duration so you can see which ones your team controls.
What should we do with legacy kcreg scripts?
Treat kcreg scripts as code to be inventoried and replaced, not carried forward unchanged. The kcreg client registration tool has a deprecated default provider, so scripts that depend on it should move to kcadm or the Admin REST API, authenticated through a dedicated service account. Start by listing every script, what it changes, which credentials it uses and where it runs. Then rewrite each one with clear inputs, idempotent behavior and logging, and test it in a non-production realm. Confirm the exact deprecation status and replacement steps against the current Keycloak server administration guide before you plan the migration.
How do we keep the automation account from becoming a security risk?
Give the automation its own service account with only the realm roles and client scopes needed for each task, instead of a shared administrator login. Store its client secret or credentials in a managed secrets store, restrict where tokens can be used, and log every change the automation makes. Reviewers should test what the account can do, including whether it can escalate its own privileges. Review the setup again when new tasks are added. Ask the partner to show how they test the account's permissions, since a broad role on one script can expose every realm it touches.
What testing and review should the automation pass before production?
Each script should run against a test realm with the same client types, roles and identity providers as production, and reruns should produce no unintended changes. Reviewers should check error handling, partial failure behavior, logging and the permissions of the service account. For higher-risk changes, such as deleting users or altering client secrets, require a second approval and a documented rollback step. Keep the test evidence with the code so auditors can see what was tested and when. Confirm the review steps and approval roles in the written scope before work begins.
How automation requests reach the Keycloak admin endpoint
The diagram starts with a pipeline or script running kcadm or an admin client library, which obtains a token from a service account client in the target realm. The request then crosses the trust boundary into the admin hostname exposed by the reverse proxy, where Keycloak checks the service account's admin roles before it writes to the database. Check that the admin endpoint is reachable only from the automation network, that the service account holds only the roles its job needs, and that admin events are recorded for every change.
Automation requests cross a trust boundary before any admin change is written.
How DeployOpen scopes and delivers Keycloak admin automation
Admin automation starts with a written scope that names every realm, every operation and every role the scripts will touch. DeployOpen agrees this scope in writing before work begins, so the client knows which realms are in scope, which user, client and role operations will be scripted with kcadm or the Admin REST API, and which manual administration stays in the Keycloak admin console. The scope also records the service account and client credentials approach, the least-privilege admin roles each automation identity receives, and the test plan that proves those roles cannot do more than the written scope allows. Deliverables and timelines follow from that document, and the client receives a quote based on it rather than a generic price list.
Delivery happens inside the client's own infrastructure, on the Keycloak instances, networks and secret stores the client already operates. The work covers the automation code and its configuration, a runbook for each script, the role model and its justification, and a verification run against a non-production realm before anything touches production. Each deliverable is documented so that the client's platform or identity team can run and change it after handover. Before handover, the client should confirm which Keycloak version and deployment method its environment uses, because the admin endpoints and tooling details depend on that baseline.
Ongoing support is optional and sits outside the initial fixed scope. A retainer can cover reviews of scripts when Keycloak releases change admin behavior, testing of automation after upgrades, and updates to role definitions as the organization adds realms or applications. The client should ask any provider how upgrades will be tested, who approves changes to automation identities, and where the scripts and their history are stored. DeployOpen does not hold certifications or partner status for this work, so clients who need a specific credential should ask for it to be confirmed in writing.

