Codifying a Keycloak Realm
nf discover codify keycloak turns a live Keycloak realm into Netherframe code: one typed
construct per object, with references between them, so a team can adopt an existing realm
instead of porting it by hand.
How it works
- Find what exists. The realm is read through the Keycloak admin REST API (read only): clients, client scopes, protocol mappers, realm and client roles, groups and their roles, identity providers and their mappers, authentication flows with their executions, subflows and execution configs, flow bindings, default roles, default and optional client scopes, and users when asked for.
- Import it through the provider. Every object is imported through the
keycloak/keycloakprovider with its import ID (demo/<id>,demo/<parent flow alias>/<id>,demo/client/<client id>/<mapper id>, ...) and read, asterraform importdoes. The code is written from the provider's state, so it holds exactly the values the provider manages, in the provider's own attribute names. - Write the code. The module holds a secrets class, a stack with every construct, and a
build_app()factory. Beside it, an adoption manifest maps each construct's address to the import ID of the object it stands for, for adopting the realm into state.
Usage
The command authenticates as the provider does, from the provider's environment variables:
export KEYCLOAK_USER=admin
export KEYCLOAK_PASSWORD=... # or KEYCLOAK_CLIENT_ID and KEYCLOAK_CLIENT_SECRET
nf discover codify keycloak --url https://keycloak.example.com --realm acme -o identity/acme_realm.py
The provider binary comes from the provider cache (~/.nf/providers, then Terraform's plugin
cache); pin it with --provider-version or point at one with --provider-binary. A summary
of what was written, the secrets the code reads and anything not codified goes to standard
error.
| Option | Meaning |
|---|---|
--include-users |
Codify users too (left out by default: they are usually data, not configuration) |
--include-builtin |
Also codify the clients, client scopes, roles and flows every realm is created with |
--manifest PATH |
Where to write the adoption manifest (default with -o: <name>.adopt.json beside the code) |
--bindings auto\|typed\|generic |
Generated classes (OpenidClient), generic Resource constructs, or typed when the bindings are installed (default) |
--auth-realm |
Realm to authenticate in (default master) |
--insecure |
Do not verify the server's TLS certificate |
Typed code imports the generated bindings, which nf generate providers keycloak/keycloak
writes; generic code runs without them and declares the provider source itself.
What the code looks like
This excerpt shows a generated stack for a realm named demo, with the imports it needs, a
shortened DemoRealmSecrets (the generated one has a field for every secret) and build_app().
from __future__ import annotations
import os
from dataclasses import dataclass
from nf.core import App, Stack
from nf.providers.keycloak.keycloak import (
AuthenticationBindings,
AuthenticationFlow,
KeycloakProvider,
OpenidClient,
Realm,
)
@dataclass(frozen=True)
class DemoRealmSecrets:
backend_svc_client_secret: str
@classmethod
def from_env(cls) -> DemoRealmSecrets:
return cls(backend_svc_client_secret=os.environ["KEYCLOAK_DEMO_BACKEND_SVC_CLIENT_SECRET"])
class DemoRealmStack(Stack):
def __init__(self, *, nf_scope: App, secrets: DemoRealmSecrets, nf_id: str = "keycloak_demo", keycloak_url: str = "https://keycloak.example.com") -> None:
super().__init__(nf_scope=nf_scope, nf_id=nf_id)
KeycloakProvider(nf_scope=self, nf_id="keycloak", url=keycloak_url, realm="master", client_id="admin-cli")
# Realm
realm = Realm(nf_scope=self, nf_id="realm", realm="demo", access_token_lifespan="10m0s", display_name="Demo Realm")
# Authentication flows
custom_browser_flow = AuthenticationFlow(nf_scope=self, nf_id="custom_browser_flow", alias="custom browser", realm_id=realm.output.id)
AuthenticationBindings(nf_scope=self, nf_id="flow_bindings", realm_id=realm.output.id, browser_flow=custom_browser_flow.output.alias)
# Clients
backend_svc_client = OpenidClient(
nf_scope=self,
nf_id="backend_svc_client",
access_type="CONFIDENTIAL",
client_id="backend-svc",
realm_id=realm.output.id,
service_accounts_enabled=True,
client_secret=secrets.backend_svc_client_secret,
)
def build_app() -> App:
app = App(nf_id="keycloak")
DemoRealmStack(nf_scope=app, secrets=DemoRealmSecrets.from_env())
return app
What the generator does for readability and safety:
- Names. Each construct gets an explicit
nf_idfrom its name and kind (backend_svc_client,tenant_scope,custom_forms_subflow,corp_email_mapper), made unique with a numeric suffix when names collide. - References instead of IDs. Realm IDs, client and client scope IDs, role and group IDs,
parent groups, flow aliases (executions, subflows, bindings, identity provider login flows),
identity provider aliases and audience client IDs become
<construct>.output.<attribute>. Roles and clients the realm was created with (realm-management'sview-users, say) are looked up by name with data sources, so the code holds no server-specific IDs. - Defaults left out. An argument is written only when its value differs from what an object
created without it gets: what the provider plans for it, what a new object reads back with
(recorded in
created_defaults.jsonfor Keycloak 26 and provider 5.10), or the zero value. Singletons every realm has (flow bindings, default roles, default and optional client scopes) are written only when they differ from a new realm's. - No cycles. The realm's flow bindings and default scopes are written as their own resources, which refer to flows and scopes without a cycle through the realm.
- Deterministic. Objects are ordered by section, each after what it refers to, then by name; set values are sorted; the module is formatted with Ruff.
Secrets
Secrets are never written into the code. The generated secrets class has a field for each one,
and build_app() reads them from environment variables named after the realm and object
(KEYCLOAK_DEMO_BACKEND_SVC_CLIENT_SECRET). That covers:
- client secrets (sensitive in the provider schema);
- identity provider client secrets and LDAP bind credentials, which Keycloak never returns;
- configuration values Keycloak masks (
**********) in authenticator and mapper settings.
Store the values in your secrets manager and export them where the app runs; pass a secrets object to the stack directly to read them from somewhere else.
Adopting the realm
The code holds no import blocks. The adoption manifest
written beside it (<module>.adopt.json) names the existing object each construct stands for:
{
"format_version": 1,
"provider": {"source": "keycloak/keycloak", "config": {"client_id": "admin-cli", "realm": "master", "url": "https://keycloak.example.com"}},
"adopt": {
"keycloak_demo.keycloak_realm.realm": {"import_id": "demo"},
"keycloak_demo.keycloak_openid_client.backend_svc_client": {"import_id": "demo/6baa522f-..."}
}
}
Add the app to [tool.nf].apps (for example "identity.acme_realm:build_app") and
plan with the manifest: every object is an import, and the apply adopts them.
nf plan --app build_app --adopt-from identity/acme_realm.adopt.json
nf apply --app build_app --adopt-from identity/acme_realm.adopt.json
From Python, import the module produced by the command above and use its manifest:
def adopt_realm() -> None:
# Plans and applies against a live Keycloak and the state backend
from identity.acme_realm import build_app
hybrid = build_app().enable_hybrid_execution()
manifest = "identity/acme_realm.adopt.json"
print(hybrid.plan(adopt_from=manifest)["imports"])
hybrid.apply(adopt_from=manifest)
--auto-approve does not approve imports unless --approve-imports (or approve_imports = true in [tool.nf.config])
is given too. Addresses are in the generated stack's default nf_id; if you give the stack
another, add "stack_map": {"keycloak_demo": "actual_stack"} to the manifest. Its provider entry records where the IDs
come from, without credentials; imports use the provider configuration the app declares.
Besides the imports, the plan should only update what Keycloak cannot read back: identity
provider client secrets and masked configuration values, which the code now sets from its
inputs. Anything else is a difference between the code and the realm worth a look. Once the
realm is in state, the manifest has served its purpose: later plans need no --adopt-from.
Coverage and limits
Codified: realms, realm and client roles (composites included), groups (nested) and group roles, default roles, OpenID and SAML clients with their default and optional scopes and authentication flow overrides, OpenID and SAML client scopes, protocol mappers (typed for the common OpenID and SAML mapper types, generic otherwise), OIDC, Keycloak OIDC, SAML, Google, GitHub, Facebook and Microsoft identity providers and their mappers (custom otherwise), authentication flows, subflows at any depth, executions and execution configs, flow bindings, realm default and optional client scopes, and users. OpenID and SAML clients, scopes and mappers are verified against Keycloak 26.8 by an integration test. Objects the provider fails to import are listed under "Not codified" rather than guessed.
Also codified: LDAP/custom user federation and LDAP mappers, client authorization resources,
scopes, policies and permissions, service-account roles, required actions, realm events,
keystores, localization, user profiles, client policies, organizations, user roles and group
memberships. Organization memberships require --include-users. Built-in flows and their
executions are included with --include-builtin. Unknown provider types are reported explicitly.
When the provider's schema exposes the importable keycloak_realm_client_policy_configuration
singleton, codification chooses it instead of writing overlapping profile/policy resources.
Select the binary with --provider-binary and pin its release with --provider-version;
a versioned binary file name (terraform-provider-keycloak_v5.10.0) is recognized too. The
generated provider and manifest preserve the pin. Regenerate bindings from the same provider
schema when using typed code.
The public upstream provider remains supported. Types it cannot import, including user profiles
and individual client policy profiles/policies, are reported under "Not codified" and omitted;
their create handlers cannot safely adopt an existing object. The remaining objects can still
be codified and adopted. Some built-in clients also fail upstream secret reads with HTTP 403
when --include-builtin is used; those failures are reported without stopping codification.
For types with an idempotent create handler, such as organization memberships, codification can read the provider's state and emit configuration without an adoption entry. Those resources appear as reviewed creates. Other import failures remain failures. Empty legacy SAML enums, keystore algorithms and LDAP settings that the provider reads but refuses to configure are replaced with valid provider defaults, with a review notice. These adjustments and unreadable secrets can produce updates alongside imports.
The generated bindings type list arguments as list[str], so a list holding references
(default_scopes=[tenant_scope.output.name, "email"], role_ids=[...]) runs but does not
type-check yet.