Skip to content
Hands-on IT IT Drills

Day 8: Keycloak Provider – Login as Code

Goal: Start Keycloak with OpenTofu and set it up in a second configuration: realm, role, client, and user for notes. Along the way, learn why a provider shouldn’t depend on resources of the same configuration, and how one configuration reads the outputs of another. · Duration: approx. 90 min · Prerequisite: Day 7

Briefing

  • The Keycloak provider manages realms, clients, roles, groups, and users through Keycloak’s Admin API.
  • A provider is configured before the plan. If its credentials depend on a resource that is only created in the same run, there is nothing to connect to during the first plan. That’s why there are two configurations: server starts Keycloak, config sets it up.
  • data "terraform_remote_state" reads the outputs of another configuration – here the server’s address.
 tag08/server  (provider docker)    ─► container keycloak :8180 ─► output url
 tag08/config  (provider keycloak)  ─► reads url via terraform_remote_state
                                    ─► realm notes, role, client, user anna

Drill 1: Keycloak as a Container

mkdir -p ~/tf-lab/tag08/server && cd ~/tf-lab/tag08/server
cat > main.tf <<'EOF'
terraform {
  required_providers {
    docker = {
      source  = "kreuzwerker/docker"
      version = "~> 4.6"
    }
  }
}

provider "docker" {}

variable "admin_passwort" {
  type      = string
  sensitive = true
  default   = "lab-admin-pw-123"
}

resource "docker_image" "keycloak" {
  name         = "quay.io/keycloak/keycloak:26.8.1"
  keep_locally = true
}

locals {
  bereit = join(" && ", [
    "exec 3<>/dev/tcp/127.0.0.1/9000",
    "printf 'GET /health/ready HTTP/1.0\\r\\n\\r\\n' >&3",
    "grep -q UP <&3",
  ])
}

resource "docker_container" "keycloak" {
  name    = "keycloak-tag08"
  image   = docker_image.keycloak.image_id
  command = ["start-dev"]
  env = [
    "KC_BOOTSTRAP_ADMIN_USERNAME=admin",
    "KC_BOOTSTRAP_ADMIN_PASSWORD=${var.admin_passwort}",
    "KC_HEALTH_ENABLED=true",
  ]
  ports {
    internal = 8080
    external = 8180
    ip       = "127.0.0.1"
  }
  healthcheck {
    test     = ["CMD-SHELL", local.bereit]
    interval = "5s"
    retries  = 60
  }
  wait         = true
  wait_timeout = 300
}

output "url" {
  value = "http://127.0.0.1:8180"
}
EOF
tofu init -no-color >/dev/null
tofu apply -auto-approve -no-color | grep -E 'Apply complete'
curl -s http://127.0.0.1:8180/realms/master | jq -r .realm

Expected (the first time, with the download, a few minutes):

Apply complete! Resources: 2 added, 0 changed, 0 destroyed.
master

start-dev starts Keycloak without an external database – enough for the lab. The health check queries management port 9000; wait = true makes OpenTofu wait until Keycloak is ready.

Save your progress? Sign up for free

Drill 2: A Second Configuration

mkdir -p ~/tf-lab/tag08/config && cd ~/tf-lab/tag08/config
cat > versions.tf <<'EOF'
terraform {
  required_providers {
    keycloak = {
      source  = "keycloak/keycloak"
      version = "~> 5.10"
    }
  }
}

data "terraform_remote_state" "server" {
  backend = "local"
  config = {
    path = "${path.module}/../server/terraform.tfstate"
  }
}

variable "admin_passwort" {
  type      = string
  sensitive = true
  default   = "lab-admin-pw-123"
}

provider "keycloak" {
  url       = data.terraform_remote_state.server.outputs.url
  realm     = "master"
  client_id = "admin-cli"
  username  = "admin"
  password  = var.admin_passwort
}
EOF
tofu init -no-color | grep -E 'Installed|initialized'
tofu apply -auto-approve -no-color | grep -E 'Apply complete'
echo 'data.terraform_remote_state.server.outputs.url' | tofu console

Expected:

- Installed keycloak/keycloak v5.10.0 (signed, key ID A63FAED146E27E2A)
OpenTofu has been successfully initialized!
Apply complete! Resources: 0 added, 0 changed, 0 destroyed.
"http://127.0.0.1:8180"

The first apply creates nothing, but it reads the data source and stores it in the state – before that, the console would only know “(known after apply)”.

The provider gets its address from the state of the server configuration. The two configurations are coupled only through this one interface: the outputs. If you start the server somewhere else, you only change something there.

Save your progress? Sign up for free

Drill 3: Realm, Role, Client, User

cat > realm.tf <<'EOF'
resource "keycloak_realm" "notes" {
  realm        = "notes"
  enabled      = true
  display_name = "notes"
}

resource "keycloak_role" "schreiben" {
  realm_id    = keycloak_realm.notes.id
  name        = "notes-schreiben"
  description = "Darf Notizen anlegen"
}

resource "keycloak_openid_client" "cli" {
  realm_id                     = keycloak_realm.notes.id
  client_id                    = "notes-cli"
  access_type                  = "CONFIDENTIAL"
  client_secret                = "lab-client-secret-123"
  direct_access_grants_enabled = true
  standard_flow_enabled        = false
}

resource "keycloak_user" "anna" {
  realm_id       = keycloak_realm.notes.id
  username       = "anna"
  email          = "[email protected]"
  email_verified = true
  first_name     = "Anna"
  last_name      = "Lab"
  initial_password {
    value     = "lab-user-pw-123"
    temporary = false
  }
}
EOF
cat > rollen.tf <<'EOF'
resource "keycloak_user_roles" "anna" {
  realm_id = keycloak_realm.notes.id
  user_id  = keycloak_user.anna.id
  role_ids = [keycloak_role.schreiben.id]
}
EOF
tofu apply -auto-approve -no-color | grep -E 'Apply complete'

Expected:

Apply complete! Resources: 5 added, 0 changed, 0 destroyed.

A complete realm from code, without a single click in the admin console. A token for anna shows whether it works:

K=http://127.0.0.1:8180
URL=$K/realms/notes/protocol/openid-connect/token
T=$(curl -s $URL -d grant_type=password -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 -d username=anna -d password=lab-user-pw-123 \
  | jq -r .access_token)
echo "$T" | jq -R 'split(".")[1] | @base64d | fromjson | .realm_access'

Expected:

{
  "roles": [
    "notes-schreiben"
  ]
}
  • The curl call is a login with username and password (password grant): client ID and secret, plus anna’s credentials. The response is JSON; jq -r extracts the token.
  • A token (JWT) consists of three parts separated by dots. The middle one is Base64-encoded JSON. jq -R reads the token as text, split splits it, @base64d decodes, fromjson turns it back into JSON.
  • The token contains the role notes-schreiben – exactly what notes-api checks before creating a note.

Save your progress? Sign up for free

Drill 4: Drift in Keycloak

Someone changes the display name in the console – here via the Admin API:

A=$(curl -s -d grant_type=password -d client_id=admin-cli -d username=admin \
  -d password=lab-admin-pw-123 \
  $K/realms/master/protocol/openid-connect/token | jq -r .access_token)
curl -s -X PUT -H "Authorization: Bearer $A" -H 'Content-Type: application/json' \
  -d '{"displayName":"von Hand geändert"}' $K/admin/realms/notes
tofu plan -no-color | grep -E 'display_name|Plan:'
tofu apply -auto-approve -no-color | grep -E 'Apply complete'
curl -s http://127.0.0.1:8180/realms/notes | jq -r .realm

Expected:

      ~ display_name                             = "von Hand geändert" -> "notes"
Plan: 0 to add, 1 to change, 0 to destroy.
Apply complete! Resources: 0 added, 1 changed, 0 destroyed.
notes

Just like with Docker and Kubernetes: the code wins. Teams that manage Keycloak with OpenTofu lock the admin console against changes to these realms – or bring every change into the code.

Save your progress? Sign up for free

Drill 5: Who Tears Down What

tofu plan -destroy -no-color | grep 'Plan:'
cd ../server && tofu plan -destroy -no-color | grep 'Plan:'

Expected:

Plan: 0 to add, 0 to change, 5 to destroy.
Plan: 0 to add, 0 to change, 2 to destroy.

Each configuration only tears down what’s in its state. The order matters: first config, then server. The other way around, the Keycloak provider would find no Keycloak left during teardown – and the state of config would be left with five orphaned entries.

Save your progress? Sign up for free

Checkpoint

cd ~/tf-lab/tag08/config && tofu state list | wc -l

Expected: five resources and the data source.

6
curl -s http://127.0.0.1:8180/realms/notes | jq -r .realm

Expected:

notes
tofu plan -detailed-exitcode -no-color >/dev/null; echo "Exit: $?"

Expected:

Exit: 0

Challenge

Roles shouldn’t be attached to individual users, but to a group schreiber. Create the group with the role, put anna into it, and remove the direct role mapping. The role must still appear in the token.

Hint: keycloak_group, keycloak_group_roles, keycloak_user_groups.

Solution

cat > gruppe.tf <<'EOF'
resource "keycloak_group" "schreiber" {
  realm_id = keycloak_realm.notes.id
  name     = "schreiber"
}

resource "keycloak_group_roles" "schreiber" {
  realm_id = keycloak_realm.notes.id
  group_id = keycloak_group.schreiber.id
  role_ids = [keycloak_role.schreiben.id]
}

resource "keycloak_user_groups" "anna" {
  realm_id  = keycloak_realm.notes.id
  user_id   = keycloak_user.anna.id
  group_ids = [keycloak_group.schreiber.id]
}
EOF
rm rollen.tf
tofu apply -auto-approve -no-color | grep -E 'Apply complete'
T=$(curl -s $URL -d grant_type=password -d client_id=notes-cli \
  -d client_secret=lab-client-secret-123 -d username=anna -d password=lab-user-pw-123 \
  | jq -r .access_token)
echo "$T" | jq -R 'split(".")[1] | @base64d | fromjson | .realm_access'

Expected:

Apply complete! Resources: 3 added, 0 changed, 1 destroyed.
{
  "roles": [
    "notes-schreiben"
  ]
}

The direct mapping lived in its own file – rm rollen.tf removes it from the code, OpenTofu removes it from Keycloak. OpenTofu creates the group and removes the direct role in the same run. The order within a run is not guaranteed – if you must avoid a gap, take two steps: first the group, then remove the role.

Save your progress? Sign up for free

Enterprise Note

  • Provider access: Instead of the admin account with a password, use a dedicated client with a service account and only the necessary roles from realm-management.
  • Remote state instead of a file path: With a shared backend (Day 9), terraform_remote_state reads from S3 instead of a local file – that then works in CI too.
  • Users rarely belong in the code: Realms, clients, roles, and groups yes; real users come from a directory (LDAP, AD) or sign up themselves.