Keycloak Terraform Provider Tutorial: Identity as Code
Terraform manages Keycloak through the provider's calls to the Keycloak Admin REST API. The safe setup is a dedicated service-account client with scoped roles, a pinned provider version, and encrypted remote state. Realms, clients, roles, scopes and mappers belong in code. Users and sessions belong to runtime.
A common first failure in identity-as-code is a pipeline that works on day one because it holds the master admin password. Six months later, nobody can say who can change what. This Keycloak Terraform provider tutorial builds the setup in the opposite order: credentials first, then state, then resources. My thesis is that the provider is easy to run and hard to run safely, so most of the effort belongs in the boundaries around it.
Key takeaways- Give Terraform its own confidential service-account client in the master realm, with only the realm-management roles it needs, not the full admin role.- State holds secrets, so use a remote backend with locking, encryption and tight access, and pass the client secret through a sensitive variable.- Set every security-relevant realm value explicitly, so a Keycloak upgrade cannot quietly change your defaults.- Manage structure (realms, clients, roles, mappers) in code and leave users and sessions alone. Import existing realms on a copy first.- Verify with an empty plan and a real token, and put prevent_destroy on realms before anyone else touches the repo.The short answer: how the Keycloak Terraform provider works
The provider is a client for the Admin REST API. Each resource you declare becomes API calls made with whatever identity you configured. That identity's permissions are the real ceiling on what a bad plan, a leaked CI variable or a compromised runner can do.
The provider lives in the keycloak organization on GitHub, under keycloak/terraform-provider-keycloak. Older tutorials use the earlier mrparkers/keycloak source address. A 2023 walkthrough for Keycloak 21 does exactly that, and its provider block pins >= 4.0.0. Check the registry for the current source address and version before copying any snippet.
What belongs in code
Put anything that defines how applications authenticate into Terraform:
- Realms and their security settings.
- Clients and redirect URIs.
- Realm and client roles, plus client scopes.
- Protocol mappers.
Leave users, credentials and sessions to runtime. They change constantly and carry personal data. Putting them in state spreads that data into a place it was never meant to be. That is a GDPR problem as much as an engineering one.
What the provider does not cover
Coverage is uneven. A September 2025 discussion reported that the provider code defines many openid_client_authorization resources but only two appear in the docs. The author, running v5.4.0 with OpenTofu, could not create a role policy resource. A 2022 issue asked for consent-screen URL attributes on keycloak_openid_client, and the page still showed it open.
These are single reports, not a coverage audit. They are clues that fine-grained authorization and newer UI fields may need manual work or a different tool. Check the resource list for what you need before committing to full coverage.
Prerequisites
You need four things before writing a line of HCL:
- A running Keycloak, reachable over HTTPS. Use a recent Quarkus-based release and read the provider's compatibility notes for your version pair. Provider and server versions drift apart, and the mismatch shows up as odd plan diffs.
- Terraform or OpenTofu. Both work with this provider. The discussion above reports OpenTofu use, but pick one per repository so state and lock files stay consistent.
- A remote backend with locking. S3 with locking, GCS or a similar backend all work. Local state on a laptop is how two people overwrite each other.
- A secrets store or CI variables, and a throwaway Keycloak. The throwaway instance is not optional. You will test destroy-and-recreate behaviour on it, and you do not want to learn that on production.
Practical rule: Never point a new Terraform configuration at a Keycloak you cannot rebuild.
Step 1: Create a least-privilege service account client

Create this client once, by hand, in the master realm. Terraform cannot create the identity it authenticates with.
Client settings
The Keycloak 21 walkthrough uses these capability settings, and I agree with them:
- Client authentication: on.
- Standard flow: off.
- Direct access grants: off.
- Service accounts roles: on.
That makes a confidential, machine-only client. There is no browser login path and no password grant, so a stolen secret can obtain only what the service account's roles allow.
Do not stop at "assign admin"
The same walkthrough then assigns the admin role, so the client has every permission. That is the point where many tutorials end. It is convenient, and it is also the highest-risk choice available.
Assign realm-management roles such as manage-realm, manage-clients and manage-users only as the configuration needs them. If you never manage users in code, skip manage-users. Role names and where they appear in the console vary by Keycloak version, so check your server's documentation.
Credential approach | Blast radius | Where it misleads |
|---|---|---|
Master admin username and password | Everything, including other realms | Works instantly, so it never gets replaced |
Service account with the | Everything, but revocable | Looks safer than a password; the permissions are the same |
Service account with scoped realm-management roles | Only the realms and objects you grant | A missing role surfaces as a 403 mid-apply, not at plan time |
The third row costs a little friction. A partial apply from a 403 is annoying, but it is far cheaper than an over-privileged CI job.
Store the secret properly
Copy the client secret from the Credentials tab straight into your secrets manager. Never commit it, and never echo it in CI output. Mask the variable in your CI system, and rotate the secret if it ever appears in a log.
Step 2: Configure the provider and remote state
Pin the provider and keep credentials out of the file:
terraform {
required_providers {
keycloak = {
source = "keycloak/keycloak"
version = "~> 5.0" # example constraint; pin to the version you tested
}
}
}
variable "keycloak_client_secret" {
type = string
sensitive = true
}
provider "keycloak" {
url = "https://sso.example.com"
client_id = "terraform"
client_secret = var.keycloak_client_secret
}The constraint above is an example. Confirm the source address and current versions on the registry page. Pinning matters because a provider upgrade can change plan output across every environment at once.
Why state is the sensitive part
HashiCorp's guidance on sensitive data says that secrets placed in configuration end up in Terraform's state and plan files. That applies to every client secret this provider reads or generates. Marking a variable sensitive hides it from CLI output. It does not remove it from state.
So treat the state bucket like a secrets store:
- Enable encryption at rest.
- Restrict read access to the people and pipelines that apply.
- Turn on locking and versioning.
- Do not let plan files linger as CI artifacts.
You can set TF_VAR_keycloak_client_secret as an environment variable instead of passing it on the command line. Shell history is another place secrets leak.
Prove authentication before writing resources
Run terraform init, then terraform plan against the test instance with no resources defined. If authentication fails, you find out now, with an empty configuration, instead of in the middle of a realm definition.
Step 3: Define a realm and its security baseline
A realm is the blast-radius boundary in Keycloak, so define it in one module:
resource "keycloak_realm" "main" {
realm = "example"
enabled = true
ssl_required = "external"
password_policy = "length(12) and notUsername"
access_token_lifespan = "5m"
lifecycle {
prevent_destroy = true
}
}Attribute names and accepted values depend on the provider version, so verify each against the registry docs. Brute-force protection, login options, SMTP and events settings go in the same module under their own blocks.
Set security values explicitly
Do not rely on defaults. A default is a promise by whoever maintains the code today. If a Keycloak or provider upgrade changes it, your posture changes with no diff in your repository. Explicit values turn that silent change into a visible plan.
The cost is a longer file. I accept that trade for password policy, brute-force protection, token lifespans and SSL requirement. Cosmetic settings can stay at defaults.
One module, many environments
Put realm settings in one module and let environments differ only by variables: hostnames, SMTP endpoints, token lifespans if you need shorter ones in staging. If production and staging drift structurally, staging stops predicting production.
Practical rule: If a setting affects authentication security, write it down explicitly, even when it equals the default.
Step 4: Add clients, roles and mappers
An OIDC client looks like this:
resource "keycloak_openid_client" "app" {
realm_id = keycloak_realm.main.id
client_id = "orders-web"
access_type = "PUBLIC"
standard_flow_enabled = true
pkce_code_challenge_method = "S256"
valid_redirect_uris = ["https://app.example.com/callback"]
}Use exact redirect URIs. Wildcards make open-redirect and token-theft attacks easier, and the saved convenience is a few lines. Public clients need PKCE. Confidential clients read their secret from a variable and never from a literal.
Scale with for_each
Define apps as a map and loop over it. This is a worked example with made-up names:
- Example input: a
local.appsmap with three entries:orders-web,billing-web,admin-web. - Action: add a fourth entry,
reports-web, with its redirect URI. - Expected plan:
1 to add, 0 to change, 0 to destroy.
If the plan shows a change or destroy on the existing three, the refactor altered resource addresses and you should stop. Changing a for_each key renames a resource instance in state. Terraform will destroy and recreate it.
Roles and mappers
Define realm and client roles, then bind them with role mappings. Add protocol mappers only for claims your services actually read. Keep claim names in a shared locals block. A claim renamed in one place and not the other fails quietly: tokens still issue, and authorization breaks downstream.
Step 5 (Optional): Import existing configuration into state
Skip this if you are starting a new realm. If one already runs in production, you have two routes: terraform import per resource, or generated configuration where your Terraform version supports it. Either way, iterate on terraform plan until the diff is empty.
Do the work on a copy of the realm first. Import is tedious. Each client, role and mapper needs its own identifier, and the first plans will show differences you must settle one by one. You decide whether each difference is the code's mistake or the server's.
The honest limitation: import covers only what you import. Anything you forget stays unmanaged, and Terraform will never report drift on it. An empty plan means the imported objects match, not that the realm matches.
For deeper platform notes beyond this guide, see more platform engineering notes.
Verify the result and roll back safely
Check the plan, then the token
First, run terraform plan and expect no changes. A non-empty plan right after apply usually means a provider quirk or a value Keycloak normalizes. Fix it now, or every future plan will carry noise that hides real changes.
Then prove the configuration works. Request a token for the new client with the client-credentials or authorization flow, decode it, and confirm the claims and roles match what you defined.
Review plans like code
Run plan in CI and require a human to read it. Watch for destroy-and-recreate on realms or clients. Recreating a client changes its internal identifier and can invalidate secrets and sessions. Recreating a realm is far worse.
Roll back
- Bad change: revert the commit and apply. That is why identity lives in version control.
- Lost state: restore from a realm export or a database backup, then re-import.
- Accidental realm deletion:
prevent_destroymakes Terraform refuse. It is not a substitute for backups.
Reporting rule: Report an identity change as "plan reviewed, applied, token verified", never just "applied".
I run identity as code in my own work, and I write about the background in my background running platform, security and identity. If you would rather not operate the server at all, one of my side projects including a managed Keycloak offering is aimed at that, though it is listed as coming soon.
Set this week's rollout plan
- Stand up a throwaway Keycloak and create the
terraformclient in the master realm with service accounts on and standard flow off. - Assign only the realm-management roles your configuration needs, and store the secret in your secrets manager.
- Configure a pinned provider and an encrypted, locked remote backend, then run
initand an emptyplan. - Write the realm module with explicit security values and
prevent_destroy, then add one client through afor_eachmap. - Apply on the throwaway instance, confirm the next plan is empty, and decode a real token.
- Add CI plan review that flags any destroy, then repeat on production, importing existing objects on a copy first.