Keycloak on GKE — from Terraform state to a working login
I built a Keycloak deployment on Google Cloud with Terraform, GKE, Cloud SQL, Helm, and GitHub Actions. Getting a container to start was the small part. The interesting question was what happens when I destroy the workload, recreate it, and ask the same pipeline to produce a working login again.
The database gets a different private IP. The cluster credentials change. An ingress admission webhook needs a network path that the application never uses. Keycloak needs to advertise the public HTTPS URL even though the proxy talks HTTP to it. And if an upgrade changes the database schema, rolling back a container does not put the database back.
Those are the parts this post follows, using code from the project. The repository is private; file paths below identify where the excerpts live. Some excerpts select fields from larger resources, and those are labelled rather than presented as complete configuration. This describes the implementation, including its remaining gaps, rather than claiming a production certification or a completed recovery drill.
The shape of the system
There are two paths worth drawing separately:
Login request:
browser → HTTPS load balancer / ingress-nginx
→ Keycloak on GKE → PostgreSQL on Cloud SQL
Deployment:
GitHub Actions → Google OIDC federation → CI service account
→ Terraform apply → outputs → Kubernetes Secrets + Helm
Keycloak runs with three replicas. Its persistent data lives in PostgreSQL, outside the cluster. The GKE worker nodes have private addresses; Cloud SQL has no public IPv4 address. Cloud NAT provides outbound connectivity, and Private Service Access connects the VPC to the managed database network.
Three Keycloak replicas alone do not establish high availability. The cluster is zonal, database availability is configurable, and there is no claim here that failover under load has been tested. The useful starting point is understanding which component owns each piece of state:
| Component | What it owns |
|---|---|
| Terraform bootstrap | APIs, CI service account, federation and permissions |
| Terraform workload root | VPC, GKE, Cloud SQL, database credentials, monitoring |
| Helm | Keycloak's Kubernetes resources and runtime configuration |
| Cloud SQL | Realms, users, clients and other persisted Keycloak data |
| Realm JSON | Initial realm/client configuration for a new database |
That last distinction matters later: a tracked realm file is not automatically a reconciler for an existing realm.
Bootstrapping the identity that deploys the infrastructure
A pipeline cannot use a federation provider it has not created yet. Terraform cannot initialize a GCS backend whose bucket does not exist either.
I split the project into a seed layer and a workload layer:
terraform/bootstrap/ APIs, federation, CI identity
terraform/ network, database, cluster, monitoring
helm/keycloakx/ shared and environment-specific values
scripts/ deployment, secrets, realm import, recovery
.github/workflows/ validation, plan, dev/prod deployment
The state bucket is prepared before backend initialization. Bootstrap is applied locally, with its own state. Routine destruction of the workload does not remove the identity needed for the next deployment.
GitHub Actions authenticates through Google's Workload Identity Federation instead of a downloaded service-account key. In terraform/modules/iam/main.tf, the OIDC provider maps GitHub claims and restricts the accepted repository. Selected fields:
oidc {
issuer_uri = "https://token.actions.githubusercontent.com"
}
attribute_mapping = {
"google.subject" = "assertion.sub"
"attribute.actor" = "assertion.actor"
"attribute.aud" = "assertion.aud"
"attribute.repository" = "assertion.repository"
"attribute.ref" = "assertion.ref"
}
attribute_condition = "assertion.repository_owner == '${var.github_owner}' && assertion.repository == '${var.github_owner}/${var.github_repo}'"
The service-account binding then selects that repository:
resource "google_service_account_iam_member" "wif_user" {
service_account_id = google_service_account.ci.name
role = "roles/iam.workloadIdentityUser"
member = "principalSet://iam.googleapis.com/${google_iam_workload_identity_pool.github.name}/attribute.repository/${var.github_owner}/${var.github_repo}"
}
The repository restriction covers both PR plans and deployments, whose subject claims differ. It is intentionally not a main-branch-only binding. That also exposes a limitation: the plan workflow and the deploy workflow currently use the same broadly privileged service account. A GitHub Environment gate controls when a job runs; it does not make those credentials read-only after authentication. Separate planner and deployer identities would improve this design.
This federation is also distinct from GKE's workload identity configuration. One authenticates the external CI runner to Google Cloud. The other configures identity for workloads running inside the cluster.
Private networking has more than one address range
The networking module creates a custom VPC and a subnet with separate secondary ranges for pods and Services:
secondary_ip_range {
range_name = var.pods_secondary_range_name
ip_cidr_range = var.pods_secondary_range_cidr
}
secondary_ip_range {
range_name = var.services_secondary_range_name
ip_cidr_range = var.services_secondary_range_cidr
}
Those ranges are consumed by the GKE cluster's IP allocation policy. Cloud SQL needs a separate range for Private Service Access, reserved for the service-provider network:
resource "google_compute_global_address" "private_service_range" {
project = var.project_id
name = var.private_service_range_name
purpose = "VPC_PEERING"
address_type = "INTERNAL"
prefix_length = var.private_service_range_prefix
network = google_compute_network.this.id
}
resource "google_service_networking_connection" "private_service_access" {
network = google_compute_network.this.id
service = "servicenetworking.googleapis.com"
reserved_peering_ranges = [google_compute_global_address.private_service_range.name]
deletion_policy = "ABANDON"
}
These are different allocations with different jobs: node subnet, pod range, Service range, and managed-service range. Treating them as interchangeable makes debugging routes much harder.
ABANDON is a teardown trade-off. The code uses it to avoid blocking destruction on the peering connection; it does not promise that every provider-side networking resource disappears with the Terraform stack.
The GKE module configures private workers while retaining a public control-plane endpoint for the GitHub-hosted runner. Selected cluster fields:
private_cluster_config {
enable_private_nodes = var.enable_private_nodes
enable_private_endpoint = false
master_ipv4_cidr_block = var.master_ipv4_cidr_block
}
workload_identity_config {
workload_pool = var.workload_pool
}
“Private nodes” describes worker addressing. It does not describe the exposure of the Kubernetes API. The implementation makes that distinction explicit; restricting control-plane access would require a different runner/access arrangement.
The webhook timeout that pod health could not explain
One failure documented in the project was an ingress admission webhook timeout. Keycloak's health was not the relevant signal. The Kubernetes API server was trying to call the ingress controller's validating webhook.
The path was:
CI creates Ingress → Kubernetes API server → admission webhook on a node
The networking module adds a firewall rule for that control-plane-to-webhook path:
resource "google_compute_firewall" "master_to_node_webhooks" {
project = var.project_id
name = "${var.network_name}-master-to-webhooks"
network = google_compute_network.this.id
direction = "INGRESS"
source_ranges = [var.master_ipv4_cidr_block]
allow {
protocol = "tcp"
ports = var.webhook_ports
}
}
The rule uses the control-plane source range and configured webhook ports. It currently has no target tags or target service accounts, so its destination scope could be narrower.
What made this useful was identifying the caller. A healthy application cannot prove that the API server can reach a controller's admission endpoint. They are separate requests, with separate firewall requirements.
Database identity must survive a cold recreate
The Cloud SQL module disables public IPv4 and requires encrypted connections. Selected fields from the instance settings:
backup_configuration {
enabled = true
start_time = var.backup_start_time
point_in_time_recovery_enabled = var.point_in_time_recovery
}
ip_configuration {
ipv4_enabled = false
private_network = var.private_network_self_link
ssl_mode = "ENCRYPTED_ONLY"
}
The password is generated by Terraform:
resource "random_password" "db_password" {
length = 24
special = true
override_special = "_%@"
}
There is also a small naming detail that matters when rehearsing destruction and recreation:
resource "random_id" "instance_suffix" {
byte_length = 2
}
The instance name appends this suffix to var.instance_name. The project documents Cloud SQL instance-name reuse as a cold-start problem; the suffix avoids relying on the same fixed name being immediately reusable. The random ID is stable while its Terraform resource remains in state. Replacing only the SQL instance does not itself regenerate the suffix.
The database address is allocated during provisioning. Hardcoding it into Helm values would make the next recreation depend on someone remembering to update a second copy.
In scripts/helm-deploy-safe.sh, the values are read from the stack that was just applied:
DB_HOST="$(terraform -chdir=terraform output -raw cloudsql_private_ip)"
KC_HOST="$(terraform -chdir=terraform output -raw keycloak_hostname)"
DB_NAME="$(terraform -chdir=terraform output -raw keycloak_db_name)"
DB_USER="$(terraform -chdir=terraform output -raw keycloak_db_user)"
The script checks those outputs for empty values before deploying. The database password takes a separate path through scripts/prepare-keycloak-db-secret.sh:
DB_PASS="$(terraform -chdir=terraform output -raw keycloak_db_password)"
kubectl -n "${NAMESPACE}" create secret generic "${SECRET_NAME}" \
--from-literal="${KEY_NAME}=${DB_PASS}" \
--dry-run=client -o yaml | kubectl apply -f -
The chart references that Secret instead of embedding the password in tracked values:
database:
vendor: postgres
existingSecret: keycloak-db
existingSecretKey: password
This keeps the credential out of the values files. It still exists in Terraform state and passes through the deployment process. Access to the backend remains access to sensitive material; a sensitive Terraform output is not encryption or secret removal.
HTTPS outside, HTTP inside, and the wrong issuer URL
For an identity provider, the public URL is part of the protocol. A page loading successfully is not enough if discovery metadata, issuer URLs, or redirects advertise the internal scheme or an unexpected path.
The shared chart values serve Keycloak at the root and configure the proxy-header mode:
http:
relativePath: /
proxy:
enabled: true
mode: xforwarded
http:
enabled: true
In this implementation, ingress-nginx sends X-Forwarded-* headers. The repository documents that using the forwarded mode instead caused Keycloak to emit HTTP issuer/redirect URLs. Those are different header formats, so the setting must match the proxy actually in front of the application.
The prod values derive the advertised HTTPS hostname from the same ingress value that deployment supplies:
extraEnv: |
- name: KC_HOSTNAME
value: {{ printf "https://%s" (index .Values.ingress.rules 0).host | quote }}
- name: KC_HOSTNAME_STRICT
value: "true"
The ingress also increases its proxy buffer:
annotations:
cert-manager.io/cluster-issuer: keycloak-issuer
nginx.ingress.kubernetes.io/proxy-buffer-size: 128k
The project records large response headers producing 502s with the default buffer. That is a different failure from the wrong issuer URL: one is response handling at the proxy, the other is URL construction inside Keycloak.
These settings explain this repository's ingress-nginx deployment. Controller choice and supported chart versions need their own review when reusing the stack.
Realm import is initialization, not ongoing reconciliation
A fresh database needs a realm and a client before there is a useful login to demonstrate. The tracked helm/keycloakx/realm-demo.json defines them without putting user passwords in Git.
Selected fields from the realm's public OIDC client:
{
"clientId": "keycloak-app-demo",
"protocol": "openid-connect",
"publicClient": true,
"standardFlowEnabled": true,
"implicitFlowEnabled": false,
"directAccessGrantsEnabled": false,
"serviceAccountsEnabled": false,
"redirectUris": ["https://www.keycloak.org/app/*"],
"webOrigins": ["https://www.keycloak.org"],
"attributes": {
"pkce.code.challenge.method": "S256"
}
}
The intended demo is an authorization-code flow with PKCE. It does not rely on enabling the password grant. Demo users are seeded separately by script.
Before Helm runs, scripts/prepare-realm-import.sh validates the JSON and publishes it as a ConfigMap:
kubectl -n "${NAMESPACE}" create configmap keycloak-realm-import \
--from-file="realm-demo.json=${REALM_FILE}" \
--dry-run=client -o yaml | kubectl apply -f -
The chart mounts it under /opt/keycloak/data/import and starts Keycloak with:
command:
- /opt/keycloak/bin/kc.sh
args:
- start
- --import-realm
The ordering is intentional. If the ConfigMap does not exist, the pod cannot mount it and can sit in ContainerCreating until deployment times out. Putting preparation inside the deployment entry point makes CI and manual deployment follow the same order.
Updating the ConfigMap is repeatable. Applying its contents to an existing realm is a different operation: startup import skips realms already present in the database. Changing this JSON therefore does not silently update a live client's configuration. Ongoing realm changes need an explicit management or migration process.
The pipeline passes values rather than rediscovering them
The reusable deployment workflow initializes the environment backend, creates a saved Terraform plan, and applies that plan:
terraform -chdir=terraform init \
-backend-config="environments/${ENVIRONMENT}/backend.hcl" -reconfigure
terraform -chdir=terraform plan \
-var-file="environments/${ENVIRONMENT}/terraform.tfvars" \
-input=false -out="${ENVIRONMENT}.plan"
terraform -chdir=terraform apply -input=false "${ENVIRONMENT}.plan"
This is a newly generated deployment plan, not promotion of the PR workflow's plan artifact. The PR plan is review feedback; the deploy job plans again against the state it sees then.
Environment deployments share one workflow implementation. Its concurrency configuration is:
concurrency:
group: terraform-${{ inputs.environment }}
cancel-in-progress: false
That serializes these deployment jobs per environment and avoids automatically interrupting a running apply when another deployment arrives. It does not coordinate every possible local Terraform invocation.
After infrastructure provisioning, the workflow obtains cluster credentials, prepares the database Secret, installs ingress and certificate components, optionally takes a database backup, and calls the Helm script. The core command is:
helm -n "${NAMESPACE}" upgrade --install "${RELEASE}" "${CHART}" \
-f "${VALUES_BASE}" \
-f "${VALUES_ENV}" \
--set "database.hostname=${DB_HOST}" \
--set "database.database=${DB_NAME}" \
--set "database.username=${DB_USER}" \
--set "ingress.rules[0].host=${KC_HOST}" \
--set "ingress.tls[0].hosts[0]=${KC_HOST}" \
--wait \
--timeout "${TIMEOUT}" \
--atomic \
--cleanup-on-fail \
--history-max 20 \
"${HELM_DEBUG_FLAG[@]}"
The environment overrides shared values, and the infrastructure outputs supply the allocated addresses. The same hostname feeds both the ingress rule and its TLS host list.
There is a reproducibility gap here: the command does not pass --version. Validation also pulls the chart without a version. A repeatable configuration should pin the chart and deliberately test upgrades; retaining values files alone does not freeze the templates they configure.
A failed release has two kinds of recovery
--atomic helps when Helm remains alive to finish its failure handling. It cannot guarantee cleanup after the runner itself is cancelled or disappears.
The deployment script reads release status before upgrading and branches on pending states:
| Release state | Recovery attempted by the script |
|---|---|
pending-install | Uninstall the incomplete release |
pending-upgrade / pending-rollback | Roll back to a detected deployed revision, otherwise uninstall |
uninstalling | Attempt removal without hooks |
| Normal terminal states | Continue to upgrade --install |
That is useful intent, but the implementation still parses human-readable Helm history with positional awk fields and suppresses some recovery errors with || true. I would use structured history output and verify the resulting state before allowing another upgrade. A recovery attempt should not be described as proven recovery.
The second kind of recovery is the database. Keycloak may migrate its schema during startup. Returning Kubernetes manifests to an older revision does not reverse those SQL changes.
The deploy workflow supports an opt-in synchronous backup before Helm runs. From its pre-deploy step:
INSTANCE="$(terraform -chdir=terraform output -raw cloudsql_instance_name)"
gcloud sql backups create \
--instance="${INSTANCE}" \
--project="${{ vars.GCP_PROJECT_ID }}" \
--description="pre-deploy ${{ github.sha }}"
The commit description makes the restore point attributable to a deployment. scripts/restore-db.sh supports listing backups, restoring onto the existing instance, and point-in-time cloning into a separate instance.
For example, the PITR branch invokes:
gcloud sql instances clone "${SOURCE_INSTANCE}" "${CLONE_INSTANCE}" \
--point-in-time="${TIMESTAMP}" \
--project="${PROJECT_ID}"
A clone leaves the source instance intact, but it is not an automatic application rollback. It creates another billable database; credentials, connectivity, data checks, and any application cutover still need attention. An in-place restore overwrites current data and requires writers to be stopped first. The script prompts for confirmation and tells the operator to scale Keycloak down, but it does not perform that scaling itself.
The distinction I want to preserve is simple: release history restores deployment configuration; database recovery restores data. Both need to agree with the Keycloak version being run.
Monitoring has its own dependency problem
The realm enables the jboss-logging event listener. The monitoring module turns matching failed-login log messages into an integer delta metric. Its filter scopes the project, location, cluster, and namespace, then matches:
(
textPayload=~"LOGIN_ERROR" OR
textPayload=~"invalid_user_credentials" OR
jsonPayload.message=~"LOGIN_ERROR" OR
jsonPayload.message=~"invalid_user_credentials"
)
The alert's threshold block aligns those counts into minute intervals and sums the matching series:
condition_threshold {
filter = "metric.type=\"logging.googleapis.com/user/${google_logging_metric.keycloak_failed_logins.name}\" AND resource.type=\"k8s_container\""
comparison = "COMPARISON_GT"
threshold_value = var.failed_login_threshold_per_minute
duration = "0s"
aggregations {
alignment_period = "60s"
per_series_aligner = "ALIGN_DELTA"
cross_series_reducer = "REDUCE_SUM"
}
}
It counts matching log entries, so validating the emitted events is part of validating the alert. A threshold named “failed logins” does not by itself establish that each failed attempt produces exactly one matching entry. The zero-second duration adds no extra persistence window; it is not a promise of instant notification.
The project also documents a propagation failure: the Logging API can finish creating the metric before Monitoring can query its type. A Terraform dependency orders API operations but cannot make the second service immediately consistent.
The current workaround is:
resource "time_sleep" "wait_for_failed_login_metric" {
depends_on = [google_logging_metric.keycloak_failed_logins]
create_duration = var.metric_propagation_delay
}
The alert depends on that timer. It gives propagation time on initial creation, but it does not test readiness, and the timer is not automatically replaced whenever the metric changes. A bounded query/retry would represent the dependency more directly.
An HTTPS uptime check provides a separate external signal. It does not establish replica redundancy or validate an authorization-code flow. There is no ready-versus-desired replica alert in the current module.
What a green deployment actually checks
The deployment workflow ends by forwarding Keycloak's management port and polling readiness:
kubectl -n keycloak port-forward \
svc/keycloak-keycloakx-http 19000:9000 >/tmp/port-forward.log 2>&1 &
PF_PID=$!
trap "kill ${PF_PID}" EXIT
bash scripts/smoke-test.sh http://127.0.0.1:19000/health/ready 30 10
This deliberately works before public DNS and certificates are usable. It checks readiness through a Kubernetes port-forward, rather than through the public ingress. It also does not check every replica independently.
The earlier validation workflow runs Terraform formatting and validation for both roots, TFLint, Helm lint for dev and prod, and Checkov. Those are useful checks for configuration. They do not replace these runtime checks:
- Verify the public discovery document advertises the expected HTTPS issuer and endpoints.
- Complete the demo client's authorization-code flow with PKCE.
- Generate controlled failed-login events and follow them through logs, metric, and notification.
- Recreate the workload and confirm that the new database address reaches Helm without a manual edit.
- Exercise interrupted-release recovery and a database restore on disposable infrastructure.
These are validation targets, not results claimed by this article. I inspected the configuration and scripts for this write-up; I am not presenting a fresh cloud deployment or recovery exercise.
The part I would carry into another project is the explicit transfer of ownership. Terraform produces the database address. Helm consumes it. Realm import initializes a new database. Monitoring waits on a different API's view of a resource. Recovery accounts for both Kubernetes configuration and database state. Once those boundaries are visible in code, a successful command becomes easier to interpret—and a failed one becomes easier to investigate.