Managing Keycloak configuration with Terraform

Keep Keycloak realms, clients, roles, identity providers and flows in version control with the keycloak/keycloak Terraform provider, with planned state handling, secrets, drift detection and promotion across environments.

On this page

Why teams manage Keycloak configuration with Terraform

Teams that run several Keycloak environments often find that development, test and production realms have drifted apart because someone changed a client redirect URI, a role or an identity provider mapping by hand in the admin console. Terraform-style configuration as code keeps realm settings in version control, where every change is reviewed, repeatable and traceable to an author. The keycloak/keycloak Terraform provider lets you declare realms, clients, roles, identity providers and authentication flows as resources, then apply the same definitions to each environment. Before you start, confirm which Keycloak versions the provider release you choose supports, because provider and server versions are tied together and a mismatch is a common source of failed plans.

The provider covers the configuration that teams most often edit by hand, but it is not a full replacement for the admin console. Decide early which objects will be code-managed and which will stay manual, such as user accounts, sessions and secrets that should never sit in a repository. Tool choice is the second decision. OpenTofu is a fork of Terraform licensed under the Mozilla Public License 2.0, stewarded under the Linux Foundation and accepted to the CNCF at the Sandbox maturity level on April 23, 2025. Its website describes it as a drop-in replacement for Terraform that preserves existing workflows, and the current release cited in the supplied facts is v1.13.1, released October 1, 2026. Check that the Keycloak provider you need is available in the registry you use, and that your team's license policy accepts the tool you pick.

The approach fits best when you manage several environments, need peer review of security-relevant settings, or must show auditors a history of configuration changes. Realm export and import remains a sound choice for a one-time copy or a small single-environment setup, and the import route is covered in the realm promotion topic. Terraform adds a plan step that shows what will change before anything is applied, which is useful for catching an accidental redirect URI wildcard. It also adds state, which must be stored and protected, so budget time for a remote backend with access control. Ask any partner for a written scope that names the environments, the objects to be code-managed and how drift will be detected and corrected.

Which configuration method fits which team

This table compares the five ways teams change Keycloak configuration: the admin console, realm export and import, the Operator's KeycloakRealmImport resource, kcadm or the Admin REST API, and the Terraform provider. Read each row for what the method is good for, what it leaves out of version control, and how it affects review and drift.

MethodGood forLeaves out of version controlReview and drift trade-off
Admin console editsExploring settings, testing a change in a development realm, and one-off fixes during an incidentEvery change unless someone records it; no built-in history of who changed whatNo review step by default, so drift from the intended configuration grows unnoticed
kc.sh export and importTaking a snapshot of a realm to seed a new environment or to inspect its full structureSecrets are not included, and the file reflects a point in time rather than an intended stateGood for a baseline; a re-import can overwrite changes made elsewhere, so confirm the override behavior for your version
KeycloakRealmImport on the OperatorDeclaring realm content alongside the Operator-managed Keycloak deployment on Kubernetes or OpenShiftSecrets must be supplied separately, and changes made in the running realm are not reconciled back into the resourceReviewable as a manifest, but import is a one-time action per resource, so drift still needs checking
kcadm or the Admin REST APIScripted changes to users, clients and roles, and tasks that a pipeline must runLogic lives in scripts, which you must keep current with the Keycloak version you runScripts can be reviewed, but they describe actions rather than desired state, so drift checks are your responsibility
Terraform provider (keycloak/keycloak)Declaring realms, clients, roles, identity providers and flows as desired state in version controlSecrets still need a secrets store, and settings the provider does not manage stay outside the codePlans show differences before apply, which supports review and drift detection; confirm provider coverage for your Keycloak version

How to set up the Terraform workflow for Keycloak

This sequence turns Keycloak realms, clients and roles into version-controlled code that can be planned, reviewed and promoted with the same discipline as application code. Each step ends with a check that proves the workflow works before any production realm is touched.

  1. Pin Keycloak and provider versions together

    Choose the Keycloak release your environment will run, then select a keycloak/keycloak Terraform provider version and record the pair in the repository. Confirm the exact provider compatibility with the Keycloak release you pick against the provider's own documentation and release notes before you write any resources, because the provider and server do not move in lockstep. Pin both versions in the Terraform configuration and in your environment documentation so every engineer and pipeline uses the same tested pair. Done when a clean checkout initializes with the pinned provider and the version pair is written in a file that reviewers can read.

  2. Choose a state backend with encryption

    Decide where Terraform state lives before the first apply, because state holds realm, client and identity provider details, and sometimes secret values. Use a remote backend that your security team has approved, with access limited to the pipeline and a small set of administrators. Enable state and plan encryption, which OpenTofu supports for local storage and remote backends with key providers such as AWS KMS, GCP KMS, Azure Vault, OpenBao and PBKDF2 if you use OpenTofu rather than Terraform. Confirm which encryption options your chosen tool version supports. Done when state is stored remotely, encrypted at rest, and access is tested with a non-administrator account that should be denied.

  3. Create a dedicated least-privilege service client

    Create a separate confidential client in a管理 realm, not in the realm you manage, and give its service account only the realm-management roles the modules require. Keep the client secret or certificate in your secrets manager and inject it into the pipeline at run time, never into the repository. Avoid reusing the bootstrap admin account or a human administrator's credentials. Review the granted roles with your identity team and document why each one is needed. Done when the provider authenticates with the service client and a test plan shows that an operation outside the granted roles fails.

  4. Write modules for realms and clients

    Structure the code so each realm is a module that declares its realm settings, clients, roles, groups and identity providers as inputs, with environment-specific values such as redirect URIs and hostnames passed in as variables. Keep secrets out of module inputs and reference them from your secrets store. Separate modules by ownership, so the team that owns an application can change its client module without touching realm-wide authentication flows. Done when the modules pass formatting and validation checks and a reviewer can trace each client to the application it serves.

  5. Run a plan against a non-production realm

    Point the configuration at a non-production Keycloak instance and a realm dedicated to testing, then run a plan and read it line by line. Look for unexpected deletions, changes to built-in authentication flows and resources that exist in Keycloak but not in code. Apply to the test realm and confirm the resulting configuration in the admin console and through the Admin REST API. Done when the plan output has been reviewed by a second engineer and the applied test realm matches what the code declares.

  6. Add a check that the plan is empty after apply

    Add a pipeline step that runs a plan immediately after apply and fails if it reports any changes. This catches drift caused by manual edits in the admin console, provider behavior that does not round-trip cleanly, or resources that Keycloak modifies on its own. Schedule the same check against each environment on a recurring basis so out-of-band changes are detected between releases. Record which attributes the provider normalizes so that expected differences are documented rather than silently ignored. Done when a deliberate manual change in the test realm causes the check to fail and the pipeline reports it.

  7. Promote the same code through each environment

    Promote the reviewed configuration from the test environment to staging and then to production using the same modules and the same pinned versions, changing only environment variables and secret references. Gate production apply behind an approval step and keep a record of which commit was applied to which environment. Plan the Keycloak server upgrade and the provider upgrade as separate changes, each tested in the non-production realm first. Done when production has a recorded apply tied to a commit, and the post-apply empty-plan check passes there too.

How state and secrets are handled when Keycloak config is in code

Treat the Terraform state file as one of the most sensitive artifacts in a Keycloak configuration project. State records the attributes of the resources the provider manages, and for Keycloak that includes realm settings, client definitions and client secret values. Anyone who can read the state can often read the secrets that the realm depends on, so the location and access controls for state matter as much as the code in the repository. Decide before the first apply where state will live, who can read it, who can write it, and how it is backed up. Confirm with your team's security owner whether the chosen backend's access logs and versioning meet your internal rules, because those settings sit outside the provider.

OpenTofu can encrypt state and plan files at rest, for both local storage and remote backends. The feature is documented in the OpenTofu state encryption guide and was introduced in v1.7. The supplied key providers are PBKDF2, AWS KMS, GCP KMS, OpenBao and Azure Vault. A passphrase-based PBKDF2 setup suits a small local workflow, while a cloud KMS or OpenBao key gives you key rotation and access policies managed outside the repository. Before relying on encryption, confirm which provider your team can operate, how keys are rotated, and what happens to existing state if a key is lost. Encryption protects state at rest, but it does not limit what an authorized operator can read through the provider, so pair it with least-privilege access to the backend.

Keep client secrets out of the repository, including in .tf files, terraform.tfvars and CI variables that are echoed in logs. Store the secret in a vault such as OpenBao, then have the pipeline or operator read it at apply time through a dedicated provider or a runtime variable. Where the provider can instead let Keycloak generate the secret, check whether your rotation process can still pick up the new value without a manual copy. Plan rotation as a recurring task: a rotated secret must reach both the Keycloak client and every application that uses it, and the state must be refreshed. Ask your implementation partner or internal team to document where each secret originates, who may read it, and how a compromise would be handled.

Drift detection and promotion risks to plan for

Keycloak configuration managed as code fails in predictable places: the console, the state file, provider gaps, upgrades, environment values and deletions. Each risk below is owned by a different team, so a plan needs a named decision owner and a check that runs before any change reaches production.

Console edits that bypass code

Administrators often fix a broken login flow or client setting directly in the Keycloak admin console during an incident. The next terraform plan then shows the change as drift, or silently reverts it on apply. Decide who may edit in the console, require a follow-up commit for every emergency change, and run a scheduled plan against production to surface unmanaged differences. Owner: the platform team lead, with the identity team approving exceptions.

Keycloak docs

Secrets written into state

Client secrets, LDAP bind passwords and identity provider secrets can end up in the Terraform state file in plain text. Check which attributes the provider marks as sensitive, confirm the state backend encrypts data at rest and restricts read access, and decide whether secrets come from a vault or a variable store instead of literal values. Treat state as a credential store. Owner: the security team sets the storage and access standard.

Resources the provider cannot fully express

Some Keycloak settings, such as newer authentication flow options, custom SPI provider configuration or less common client attributes, may be missing from the provider or only partly modeled. Compare each realm feature you depend on against the provider version you pin, and test an apply in a non-production realm. Where a gap exists, decide whether to accept a manual step, script it, or keep that setting outside Terraform. Owner: the identity engineering lead.

Upgrades that change resource behavior

A Keycloak upgrade can change default values, validation or how an API field behaves, so an unchanged configuration may plan differently after the server moves. Read the upgrade notes for each target version, pin the provider to a version tested against that Keycloak release, and run a plan against a staging instance before upgrading production. Breaking changes in minor releases are opt-in, so confirm which options your realms depend on. Owner: the platform team, with sign-off from the application owners.

Upgrade guide

Environment-specific values in shared code

Redirect URIs, hostnames, identity provider endpoints and client secrets differ between development, test and production, and hardcoding them in shared modules makes promotion copy the wrong values. Keep one code path with per-environment variable files, validate that production redirect URIs use the production hostname, and block a promotion whose plan changes values outside the expected list. Owner: the release engineering team, with the application owner for each client.

Deleting resources other systems depend on

Removing a client, role or identity provider from code destroys it in Keycloak, and users, service accounts, group mappings or external integrations that reference it can break at once. Review every destroy in the plan, check for dependent applications and automation before merging, and require a second approver for deletions in production. Consider a deprecation period that disables resources before removing them. Owner: the identity team lead, with input from each consuming application team.

Keycloak versions, provider releases and tool choice

Pin the Keycloak server to an exact release in your image tag, Operator channel or package, and treat that pin as an input to every Terraform run. The current release is 26.8.1, published October 13, 2026. Since Keycloak 26.0, the project plans four minor releases a year and a major release every two to three years, so an unowned pin will fall behind quickly. The project says breaking changes in a minor release are opt-in, which lowers risk but does not remove the need to test. Keep the pin in the same repository as the Terraform configuration so the two change together.

  • Current line: 26.8.1 is the reference point for choosing your pin and planning your next upgrade.
  • Opt-in breaking changes: a minor release changes behavior only when you enable the related option, so read the notes for every option you turn on.
  • 26.8 items to review: the upgrade notes cover enforced SMTP StartTLS without plaintext fallback, mandatory signature validation of backchannel logout tokens from external providers, and login failures persisted to the database by default.
  • Multi-site deprecation: the 26.8 notes recommend moving from the deprecated multi-site feature to the stateless feature, which changes how clusters are configured.

Before any upgrade, confirm which Keycloak line each environment runs and whether your Terraform configuration has been tested against that line.

How the configuration pipeline moves a change to production

The pipeline starts with a change committed to Git by an administrator or engineer, who then reviews the plan output before anything touches a running server. An approved change is applied to a test realm first, and the same code is promoted to production with its own state and variables. A scheduled plan runs against production and reports any difference made in the admin console, so drift is caught before it becomes the source of truth. Check that each environment has separate state and that no secret values appear in the repository.

Change flow from Git review through test and production, with scheduled drift checks.

Security controls for the Terraform admin path

The Terraform pipeline holds admin rights over every realm, client and identity provider, so it becomes one of the most privileged paths into Keycloak. The cards below cover the identities, secrets, state and hostname controls that keep that path narrow and visible. Review them together, because a strong service account does little if the state file or pipeline credentials expose the same rights.

Service account with least-privilege roles

The provider authenticates as a client, so the service account needs only the admin roles that the managed resources require. Start with a dedicated client in a master or admin realm, grant roles per realm where possible, and avoid the built-in admin role. Check that no one reuses this account for manual console work. Record which roles each Terraform module actually needs, because over-broad grants are the most common finding in this area.

Keycloak admin docs

State access control and encryption

The state file records realm settings, client attributes and sometimes secret values in plain form. Restrict read and write access to the state backend to the pipeline identity and a small platform group, and log access to it. OpenTofu can encrypt state and plan files at rest for local and remote backends, using key providers such as AWS KMS, GCP KMS, OpenBao or Azure Vault. Confirm which provider your organization's key management policy accepts.

Encryption introduced in
1.7
OpenTofu encryption docs

Pipeline credentials and secret injection

Keep client secrets and the service account credential out of repository files and variable files. Inject them at run time from the CI system's secret store or a vault, and scope them to the protected branch or environment that applies production changes. Short-lived tokens where your CI platform supports them reduce the exposure window if a runner is compromised. Ask your team which pipeline runners can read these secrets and whether those runners are shared with other projects.

Separating production admin rights from the pipeline

Keep the credential that applies production changes distinct from the credentials people use to sign in to the admin console. Require a reviewed merge request before a plan can be applied to production, and limit who can approve that apply. Engineers should be able to read plans without holding the rights to apply them. This separation makes it clear which changes came from code review and which came from an operator clicking in the console.

Audit logging of applied changes

Record who triggered each apply, the commit it came from, the plan that was approved and the admin events that followed in Keycloak. Enable Keycloak's admin event logging so that changes made by the service account appear alongside manual changes. Compare these logs with the state history during drift reviews. Confirm with your security team where these logs are retained and how long your policy requires them to be kept.

Protecting the admin hostname

Keycloak's production guidance says the admin console and Administration REST API should be exposed on a different hostname or context path from public frontend URLs. The Terraform provider calls that API, so point the provider at the admin hostname and restrict network access to it to the pipeline runners and administrator networks. Block the admin paths at the reverse proxy for public traffic. Test that these paths are unreachable from the public internet before the first automated apply.

Keycloak production guide

Questions teams ask before managing Keycloak with Terraform

What does it cost in effort to manage Keycloak configuration with Terraform?

The effort depends on how many realms, clients, roles and identity providers you need to codify, how many environments they must reach, and how much of your current setup is already documented. Cost has two parts: one-time work to write the provider code, import existing objects and build the pipeline, and recurring work to review changes, upgrade the provider and handle drift. Scope and environment count drive most of it. Ask any partner for a quote that lists realms in scope, environments, secrets approach, state backend, and whether existing pipelines will be reused or replaced.

How long does a Keycloak Terraform pilot take?

A pilot is usually one realm, a small set of clients and roles, one non-production environment and a pipeline that plans and applies changes. Its length depends on the Keycloak version you run, how clean your existing configuration is, access to a test instance, how your secrets and state storage are approved, and how quickly reviewers can sign off on the plan output. No duration is set in this page. Ask for a timeline tied to a written scope and to named dependencies, including access, approvals and the environments that must exist before work starts.

Can an internal team manage Keycloak with Terraform on its own?

Yes, a capable internal team can, provided it has people who understand Keycloak's data model (realms, clients, scopes, authentication flows and identity providers), can write and review Terraform or OpenTofu code, and can operate a remote state backend with encryption and access control. Platform engineers and identity engineers usually need to work together. Expect a learning curve for the provider's resource attributes and for the differences between the provider's behavior and the admin console. Ask a partner which of these skills it will transfer to your team and what documentation it will leave behind.

Should we choose OpenTofu or Terraform for Keycloak configuration?

Both can run the keycloak/keycloak provider, so the decision is mostly about licensing, governance and your existing toolchain. OpenTofu is licensed under the Mozilla Public License 2.0 and is under Linux Foundation stewardship. It was accepted to the CNCF at the Sandbox maturity level on April 23, 2025. Its FAQ says it aims for feature parity with Terraform but does not guarantee compatibility with future Terraform releases. If you already run Terraform under a license that suits your policy, staying may be simpler. Confirm your license position and provider version support with your legal and platform teams before you commit.

How do we bring realms that were built by hand under Terraform?

The usual approach is to export the current configuration, decide which objects Terraform will own, write matching resources, and import existing objects into state before any apply runs. Run plans until they show no changes, then freeze manual edits for the codified objects. Expect some objects to be hard to model, such as generated secrets, default flows and objects created by other tools. Realm export and import can help with inventory and environment promotion, but it does not replace the code review. Ask for a plan that lists which realms are imported first and how manual changes are stopped during cutover.

How should secrets and state be handled when Keycloak is managed with Terraform?

Terraform state can contain sensitive values, including client secrets and other attributes that the provider stores. Keep state in a remote backend with access control, encryption at rest and audit logging, and keep secret values out of source control. OpenTofu can encrypt state and plan files at rest, with key providers including PBKDF2, AWS KMS, GCP KMS, OpenBao and Azure Vault. Confirm which key provider fits your key management policy and how state access is granted to CI runners. Your security team should review the backend design before the first apply.

How do we detect and handle drift between Keycloak and the code?

Drift occurs when someone changes a client, role or flow in the admin console or through the Admin REST API without updating the code. A scheduled plan run in CI will show differences as proposed changes. Decide whether drift is reverted automatically, reported for review or accepted and back-ported into the code. Also decide who can change objects directly in production and how emergency changes are recorded. Ask a partner how it will set up scheduled plans, alerts and the break-glass procedure, and whether it will document the exceptions your team must approve.

Which Keycloak version should we target before writing the provider code?

Target the Keycloak version your environments actually run, and confirm which versions the keycloak/keycloak provider supports before writing code. The current Keycloak release is 26.8.1, published October 13, 2026. Keycloak plans four minor releases a year, and since Keycloak 26.0, breaking changes in a minor release are opt-in. Provider behavior and Keycloak behavior can change together, so pin both versions and test upgrades in a non-production environment. Ask the team that will run the pipeline for its version policy and the process for testing a new Keycloak release against the codified configuration.

How DeployOpen scopes Keycloak configuration as code

DeployOpen starts this work with a realm inventory, not with Terraform code. Before anything is written, the team lists every realm, client, role, client scope, identity provider, user federation link and authentication flow that the Keycloak estate depends on, then marks which ones are owned by the platform team, which belong to application teams and which should stay outside code entirely, such as individual user accounts and bootstrap admin credentials. That inventory sets the boundary of the Terraform scope. It also surfaces the decisions that change the code, including which Keycloak versions the client runs, whether the keycloak/keycloak provider version is pinned against the Keycloak release in use, and which environments need to be promoted between.

DeployOpen writes the configuration code in the client's own repository, under the client's review and branching rules, so the history stays with the client. The work also covers how state is stored and how secrets are kept out of it. Because Terraform state can contain sensitive values, the scope usually includes a remote backend in the client's infrastructure, access restrictions on that backend, and an agreed approach to encrypting state at rest, with OpenTofu's state encryption as one option to evaluate against the client's standards. Client secrets, LDAP bind passwords and identity provider secrets are handled through the client's secret store, not committed to the repository. Confirm early which team holds the keys and who can read state files, since those answers shape the deliverables.

Every engagement is fixed-scope. Scope, deliverables and timelines are agreed in writing before work starts, and the written scope should name the environments covered, the drift check approach, the promotion steps and the handover material. Ask for the realm inventory, the state and secret design and the pipeline or procedure for running plans in writing, and check that each one is listed as a deliverable. After handover, many clients keep a retainer for Keycloak version upgrades, provider updates and recurring drift checks, because each new release can change how the provider models a setting. Retainer terms are quoted separately from the initial build.

Sources and further reading

Talk to our team.

Tell us what you're working on, whether it's a deployment, an audit, a security test or a cyber range. You'll speak with an engineer who can help you scope it.

  • 30-minute call: free, with no obligation.
  • NDA on request: we can sign before you share details.
  • Clear next steps: a scope and plan after the call.