What Is Identity as Code? A Practical Guide for Platform Teams

· 12 min read

Someone fixes a login bug by editing a redirect URI in the admin console, and nobody records the change. So, what is identity as code? It is the practice of declaring identity configuration (realms, clients, roles, flows) in versioned files, reviewing it in pull requests, and applying it with a pipeline. It looks like infrastructure as code, but the semantics differ, and teams that ignore the difference get hurt.

Key takeaways- Identity as code manages the configuration of your identity server, not the user accounts inside it. Users, passwords, sessions and consent records stay out of the repository.- The plan step is the main benefit. A reviewer sees "this client's redirect URI changes" before it ships, and drift from console edits shows up on the next plan.- Terraform state files contain secrets. Encrypt the backend, restrict access, and reference client secrets from a secret store.- Protect against destructive diffs with prevent_destroy and manual approval, because deleting a client or realm can lock out real users.- For one app, one realm and one admin with no audit requirement, the overhead probably outweighs the benefit.

What identity as code is, in one paragraph

Identity as code means the configuration of your identity system is declared in files, changed through pull requests, and applied by a pipeline calling the server's admin API. Nobody clicks through a console to create a client or grant a role. The repository is the intended state, and the pipeline makes the server match it.

The scope matters. This covers how the identity system is set up: realms, clients, scopes, roles, authentication flows. It does not cover the people who log in. Your end users are data, not configuration.

The critique you will see in top-ranking posts is fair: identity is not infrastructure. A server does not care if you recreate it. An identity provider holds live sessions, issued tokens and relationships with applications. The workflow transfers well, but the safety assumptions do not, and the rest of this guide is about that gap.

How it works: desired state, a provider and a reconcile loop

The mechanism has three parts. You write declarative files describing what should exist. A plan step compares those files with the server's actual state and prints a diff. An apply step executes that diff through the identity server's admin API.

Keycloak with Terraform

For Keycloak, the usual route is the community-maintained Terraform provider for Keycloak. Its README shows installation through a required_providers block with the source keycloak/keycloak and an example version constraint of >= 5.11.0. It also points to the Terraform Registry for full documentation and gives a terraform state replace-provider command for people migrating from the older mrparkers/keycloak provider.

The provider exposes resources for realms, clients, client scopes and roles. Exact resource names and arguments change between provider versions, so treat the registry documentation as authoritative. I run identity this way with Keycloak and Terraform, and the habit that pays off most is reading the registry page for the version you pin rather than copying snippets from old blog posts.

The state file is the record of what the code owns. Anything in state is managed. Anything on the server but not in state is invisible to Terraform until you import it.

Why the plan step matters

A console edit has no review. A plan does. Before merge, a reviewer sees a line like "valid redirect URIs: one element added" and can ask whether that host should receive authorization codes.

That is the argument for the whole practice. A redirect URI, a scope or a role grant is a security decision. The plan turns it into something a second person can read in under a minute.

Drift

Drift is any difference between the code and the live server. Someone edits a client in the console, and the next plan shows that change as a diff against your files. It is detected, not silently kept.

Detection is not the same as prevention. If the plan runs only when someone opens a pull request, drift can sit unnoticed for weeks. Schedule a plan on a timer so drift surfaces without a code change.

What belongs in code and what does not

Share of breaches involving third parties and year-over-year change
Share of breaches involving third parties and year-over-year change

The dividing line is simple: configuration goes in code, data does not.

Item

In code?

Where it misleads

Realms, clients, client scopes

Yes

A recreated client gets a new internal ID, which can break things that referenced the old one

Roles and group-to-role mappings

Yes

Mappings are easy to over-grant in one diff; review them as access changes

Authentication flows, token lifetimes

Yes

Provider coverage for newer flow options can lag the server

Identity provider connections

Yes

The connection's client secret must come from a secret store, not the file

End-user accounts and passwords

No

Treating users as resources invites mass deletion on a bad apply

Sessions and consent records

No

These are personal data with GDPR obligations, not configuration

Break-glass admin accounts

Outside the pipeline

If the pipeline owns them, a broken pipeline locks you out of fixing it

Secrets

Never commit client secrets. Reference them from a secret store and inject them at plan and apply time. The catch: Terraform state records the values it manages, so secrets end up in state anyway.

That means the state backend is part of your security boundary. Encrypt it, restrict who can read it, and log access. A locked-down repository with an open state bucket protects nothing.

Secrets hygiene is not an abstract concern. A 2026 analysis of the Verizon DBIR by Descope reported that third-party involvement touched 48% of breaches, up 60% year over year. It said the report traced many headline incidents to missing multi-factor authentication, poor credential rotation or missing least privilege. That is a vendor's reading of a breach report, so it is a clue about where failures cluster, not proof that code-managed identity prevents them. It does support one practical point: rotation and least privilege are worth making reviewable.

The break-glass judgment call

Keep a small set of emergency admin accounts outside the pipeline. If your pipeline, state backend or CI provider is down, you still need a way in. Document those accounts, store their credentials offline, alert on every use, and audit them regularly.

Practical rule: If it is configuration, put it in code; if it is a person or a person's data, keep it out.

Where the critique is right: limits and failure modes

The critics are not wrong. Here are the places where the infrastructure analogy breaks.

Policies do not update themselves

When application code adds an endpoint, the matching role or scope does not appear on its own. The app ships, the endpoint returns 403 for everyone, and someone "fixes" it in the console. Couple the application change and the identity change in one pull request, or at least in linked ones. I cover the same coupling principle in structuring a codebase for scale: things that change together should live together.

Provider coverage lags the server

This is the honest limitation. A new Keycloak release can add settings before the provider supports them. Some options will need a direct admin API call or a console step. Record those exceptions in the repository, in a README or a script, so they are not tribal knowledge. Otherwise they become permanent undocumented drift.

Destructive diffs

Deleting a client can break login for every user of that application. Deleting a realm is worse. Terraform will do either if the diff says so, and a renamed resource often appears as destroy-and-create.

Two protections help:

  • Set lifecycle { prevent_destroy = true } on realms and critical clients, so a plan that would destroy them fails.
  • Require manual approval on any apply whose plan contains a destroy.

The cost: prevent_destroy blocks legitimate removals too. You must edit the flag in a reviewed commit first. That friction is the point.

When not to bother

If you have one application, one realm, one administrator and no audit requirement, skip this. Setting up state, a backend, CI and secret handling takes real effort. A well-documented console setup with an exported realm backup is cheaper and adequate. Revisit when a second administrator or a compliance question appears.

Practical rule: Protect realms and production clients with prevent_destroy and manual approval, and couple every application change with its identity change.

A worked example: adding a new service client to a Keycloak realm

This is an illustrative scenario, not a recorded project. A new backend service, moderation-api, needs OIDC login and a moderator role that members of a moderators group receive.

The change

Create a branch and add four things:

  • A client for moderation-api with a single valid redirect URI.
  • A moderator role in the realm.
  • A mapping from the moderators group to that role.
  • A reference to the client secret from your secret store, never a literal.

A sketch of the client (argument names depend on your provider version; check the registry):

resource "keycloak_openid_client" "moderation_api" {
  realm_id              = keycloak_realm.main.id
  client_id             = "moderation-api"
  access_type           = "CONFIDENTIAL"
  standard_flow_enabled = true
  valid_redirect_uris   = ["https://blog.example.com/callback"]
}

What the reviewer reads

CI runs plan and posts the output. It should look roughly like this (illustrative, abbreviated):

# keycloak_openid_client.moderation_api will be created
# keycloak_role.moderator will be created
# keycloak_group_roles.moderators will be created

Plan: 3 to add, 0 to change, 0 to destroy.

The reviewer checks three things. The redirect URI is the exact expected host, with no wildcard. The role grant goes to the intended group. The summary shows 0 to destroy. Anything else in the diff is a reason to stop.

The reviewer should be someone who owns the affected application, because they know whether moderator should be able to do what the role permits.

Rollout

Apply to a staging realm first. Run a real login and inspect the token for the expected role claim. Then apply the same commit to production in the same pipeline. Adding a client and a role does not touch existing sessions, so current users stay logged in.

Rollback

Revert the commit, let CI re-plan, and apply. The plan should show the three resources being removed, which is your cue to confirm no other service started using them.

Some things do not roll back. Rotated signing keys are the clear case: once clients and services have picked up new keys, reverting your files does not restore trust in the old ones. Tokens already issued and any access already granted to third parties also stay out of reach. Plan key rotations as their own event with their own communication.

Adopting it without breaking production

The risky way to adopt is to write fresh code and apply it over a live realm. Don't.

Import first

Import your existing configuration into state before changing anything. Then run plan and keep editing the code until it shows zero changes. A clean zero-diff plan proves your code describes reality. Only then make your first real change.

Migrate by area

Start with one realm, or one family of clients. Expand by area, not all at once. Each area you move gives you a safe place to learn how the provider handles your particular settings, including the ones it does not cover.

Lock down the console

Once the pipeline is trusted, remove console write access for humans and leave read-only for debugging. Without this step, drift is a matter of discipline, and discipline erodes. A 2026 summary by Abnormal AI of the Verizon DBIR reported that 62% of breaches involved the human element. That figure covers many attack types, such as phishing and misuse, so it does not show that console edits cause breaches. It is a reasonable prompt to reduce manual access to systems that control access.

Buy versus build

If you are starting a new SaaS and want auth and billing pre-built, MakeV1: Ship your SaaS with the hard parts already done. is one starting point. Weigh it against your own identity needs, especially whether you need a standalone identity server with its own realms and flows.

You can read more about my background running platform, security and identity, and there are more notes on platform engineering if this topic is useful to you.

Common questions

Is identity as code the same as infrastructure as code?

It shares the workflow: files, review, plan, apply. The semantics differ. Identity configuration controls who can access what and holds live sessions, so a destructive change affects real users immediately. That is why destroy protection, approval gates and break-glass accounts matter more here.

Which tools support identity as code besides Terraform?

The sources I have cover Terraform only, through the Keycloak provider. Other approaches exist, such as scripts against the admin API or realm export and import, but check each tool's documentation for coverage and drift detection. Those two features are what separate real identity as code from a scripted setup.

Does identity as code help with GDPR compliance?

Indirectly. It gives you a reviewable history of who changed access rules and when, which supports accountability. It does not manage user data, consent records or deletion requests, which stay in the identity system as data. It is not a compliance program on its own.

Run this routine for every identity change

  1. Express the change as a code edit in a branch; never start in the console.
  2. Run plan in CI and read the diff for redirect URIs, scopes and role grants.
  3. Require review from someone who owns the affected application.
  4. Apply to staging, run a login and token check, then apply to production.
  5. Schedule a drift check weekly and treat any console change as an incident to explain.
  6. Review secrets, state backend access and break-glass accounts each quarter.
What Is Identity as Code? A Practical Guide for Platform Teams - Ali Hesari