Warning: restore the Kubernetes secrets before the first install attempt. An install run without the backed-up Terraform state secrets deletes the "xDM Admin" realm role and its user assignments in Keycloak.


Need

An SDP Self-Hosted instance has to be restored, for example after the loss of a cluster, or moved to a new cluster, with the data stores already restored by the organization's own tooling.

Backing up the databases, search engine indices and Kafka topics is not enough. SDP does not recreate several Kubernetes secrets, and the Keycloak setup relies on state stored in secrets. Without them, the reinstall fails or damages the Keycloak configuration.


This article describes what to back up alongside the data stores, how to restore on a new cluster (including into a namespace with a different name), how to recover from the known failures, and which checks to run afterwards.


Summarized Solution

Alongside the data stores, four items must be backed up from the SDP namespace, all at the same time: the Helm release values, the input secrets, the Keycloak admin secret and the Terraform state secrets (tfstate-*).


To restore:

  1. Restore the data stores with the organization's own tooling.
  2. Create the namespace (same name as before) and apply the backed-up secrets. This must be done before the first install attempt.
  3. Install the release with the same chart version and the backed-up values, without --wait.
  4. If the namespace name differs from the backup, rewrite the namespace recorded in the Terraform state secrets after step 2.
  5. Verify that all pods are ready and that the Keycloak realm role mappings match the state before the incident.

Without the Keycloak admin password, there is no tested restore procedure.


Detailed Solution

Prerequisites

  • kubectl, helm, jq and yq, and access to the chart.
  • With the Semarchy registry (oci://registry.na.semarchy.net/...), log in first with helm registry login registry.na.semarchy.net, otherwise the install fails with 401 unauthorized.


What is possible

Situation

Result

New cluster, data stores restored, Kubernetes secrets restored before the install

Works first time, no data difference

New cluster, data stores restored, Kubernetes secrets not backed up

Not possible without manual recovery; the first install attempt deletes the xDM Admin realm role and its mappings

Keycloak admin password lost

No tested procedure


Step 1: Back up the data stores and the namespace content

The data stores (PostgreSQL databases, search engine indices, Kafka topics if they hold needed data) are backed up with the organization's own tooling. The items below are taken from the SDP namespace, at the same time as the data stores.

Release values. The output of helm get values. It holds the license and every setting. The reinstall must use the same values and the same chart version.

Input secrets. The secrets created before the first install. SDP does not recreate them.

Secret

Keys

Used for

semarchy-harbor (type docker-registry)

.dockerconfigjson

Pulling the Semarchy images

keycloak-postgres

host, port, username, password, database

Keycloak database

dm-postgres

database-host, database-port, database-name, database-jdbc-url, semarchy-repository-role, semarchy-repository-password, semarchy-repository-ro-role, semarchy-repository-ro-password

Data Management repository

dm-postgres-datasource-<N> (one per datasource, all of them)

database-host, database-port, database-name, database-jdbc-url, semarchy-role, semarchy-password

Data Management datasources

dpc-postgres

host, port, database, schema, username, password

Data Product Catalog database

kafka-keycloak

bootstrap-servers, username, password, sasl-jaas-config

Keycloak events

dm-kafka

bootstrap-servers, username, password, sasl-jaas-config, security-protocol, consumer-group

Data Management

mcp-kafka

bootstrap-servers, username, password, sasl-jaas-config, security-protocol, consumer-group-prefix, topic

MCP server

opensearch-provider or elasticsearch-provider (global.setup.searchEngine.secret.name)

host, port, url, username, password, admin-username, admin-password, index

Search engine (Log Explorer, Billing)

mail-secret

smtpHost, smtpPort, smtpUser, smtpPassword, smtpFrom, smtpAuth, smtpStartTls, smtpSsl (plus the smtpTokenAuth* keys for OAuth2)

Keycloak emails

ca-http (global.caCert.secretName), only with a private CA

ca.crt

Trusting a private certificate authority

TLS secrets named in the ingress tls.secretName, only with an own certificate

tls.crt, tls.key

HTTPS; with cert-manager they are issued again and need no backup

Keycloak admin secret. Keycloak keeps the admin password set at the first install in its database and only stores a hash of it. A reinstall that does not provide the same password fails: every setup job gets 400 Bad Request when logging into Keycloak. The password must therefore be provided through a secret of its own:

Secret

Keys

Values setting

sdp-keycloak-admin (any name)

username, password (names set by semarchy-iam.keycloak.auth.usernameKey and passwordKey)

semarchy-iam.keycloak.auth.existingSecret

semarchy-iam:
  keycloak:
    auth:
      existingSecret: sdp-keycloak-admin

If the values do not set existingSecret yet, the chart generated the password in <release>-semarchy-iam-admin. The dedicated secret is created from it before the backup:

kubectl get secret "${RELEASE}-semarchy-iam-admin" -n "$NS" -o json |
  jq '{apiVersion:"v1", kind:"Secret", type:"Opaque", metadata:{name:"sdp-keycloak-admin"}, data:{username:.data.username, password:.data.password}}' |
  kubectl apply -n "$NS" -f -

Then, after the export below, existingSecret is added to the exported values:

yq -i '."semarchy-iam".keycloak.auth.existingSecret = "sdp-keycloak-admin"' values.yaml

Terraform states. Every secret whose name starts with tfstate- (17 in 2.0.0). They hold the state of the setup jobs and tell them that the Keycloak realm, clients and roles already exist. Without them, the install tries to create the realm again and deletes the xDM Admin role first.

The secrets and ConfigMaps written by the setup jobs (keycloak-config, keycloak-provider, *-keycloak, tenant-settings, <release>-log-explorer-aliases) need no backup: the setup jobs recreate them from the states.

Namespace in the Terraform states. 14 resources in 13 of the Terraform states are Kubernetes secrets and ConfigMaps recorded as <namespace>/<name> (metadata.namespace and the resource id). The setup jobs take the namespace from the release; nothing else stores it. Restoring into a namespace with the same name needs nothing more. For another name, see "Restore into a namespace with another name".

Kafka. SDP 2.0.0 Self-Hosted creates no Kafka user or topic: no Terraform state holds a Kafka resource. With an own Kafka cluster, only the credential secrets listed above are needed on the Kubernetes side.

Export commands. The release, the namespace and the names of the input and admin secrets are set first. The names must match the installation; the last part adds every dm-postgres-datasource-<N> secret found in the namespace, so that no datasource is forgotten:

RELEASE=semarchy
NS=semarchy
SECRETS="semarchy-harbor keycloak-postgres dm-postgres dpc-postgres kafka-keycloak dm-kafka mcp-kafka opensearch-provider mail-secret ca-http sdp-keycloak-admin $(kubectl get secret -n "$NS" -o name | sed -n 's#^secret/\(dm-postgres-datasource-[0-9]*\)$#\1#p' | paste -sd' ' -)"
echo "$SECRETS"

The values, the listed secrets and every tfstate-* secret are then exported into files. The jq filter keeps only the name, type, labels and data: the Terraform backend finds its states by label, and the other metadata (resourceVersion, uid, Helm annotations) would make the restore fail on a new cluster.

mkdir -p sdp-backup && cd sdp-backup
helm get values "$RELEASE" -n "$NS" -o yaml > values.yaml
kubectl get secret -n "$NS" -o json | jq --arg names "$SECRETS" '
  ($names | split(" ")) as $keep
  | {apiVersion:"v1", kind:"List", items:[.items[]
      | select((.metadata.name as $n | $keep | index($n)) or (.metadata.name | startswith("tfstate-")))
      | {apiVersion, kind, type, data, metadata:{name:.metadata.name, labels:(.metadata.labels // {})}}]}' > secrets.json
jq -r '.items[].metadata.name' secrets.json

Expected: every name of SECRETS and 17 tfstate-* secrets. The output is compared with echo "$SECRETS": a name missing from the output does not exist in the namespace. values.yaml and secrets.json hold credentials and must be stored like the database backups.


Step 2: Restore on a new cluster

If the old instance still runs on the same cluster, it is uninstalled first, and the workloads that helm uninstall leaves behind are deleted (they keep connecting to the databases):

helm uninstall "$RELEASE" -n "$NS" --timeout 15m
kubectl delete -n "$NS" --ignore-not-found \
  deployment/${RELEASE}-semarchy-data-platform-diag-sidecar \
  service/${RELEASE}-semarchy-data-platform-diag-sidecar \
  cronjob/${RELEASE}-semarchy-data-platform-diag-inst-job \
  cronjob/${RELEASE}-semarchy-data-platform-logs-job \
  cronjob/${RELEASE}-dpc-backend-data-location-sweep
  1. Restore the data stores with the organization's own tooling.
  2. Create the namespace with the same name as before and restore the secrets. This must be done before the first install attempt: an install that runs without the Terraform states deletes the xDM Admin role.
kubectl create namespace "$NS"
kubectl apply -n "$NS" -f secrets.json
  1. Install the release with the same chart version and the backed-up values (including semarchy-iam.keycloak.auth.existingSecret). --wait must not be used: post-install hooks create secrets the workloads need.
helm upgrade --install "$RELEASE" <chart> --version 2.0.0 -n "$NS" -f values.yaml --timeout 20m

Expected: STATUS: deployed after about 10 to 15 minutes.


Restore into a namespace with another name

After step 2 above, the namespace recorded in the Terraform states is rewritten, with OLD_NS the namespace of the backup and NS the new one:

for s in $(kubectl get secret -n "$NS" -o name | grep tfstate); do
  new=$(kubectl get "$s" -n "$NS" -o jsonpath='{.data.tfstate}' | base64 -d | gunzip |
    jq -c --arg o "$OLD_NS" --arg n "$NS" '.serial += 1 | walk(if type=="object" then
      ((if has("namespace") and .namespace==$o then .namespace=$n else . end)
      | (if (.id|type)=="string" and (.id|startswith($o+"/")) then .id=($n+"/"+(.id|ltrimstr($o+"/"))) else . end))
      else . end)' | gzip | base64 | tr -d '\n')
  kubectl patch "$s" -n "$NS" --type merge -p "{\"data\":{\"tfstate\":\"$new\"}}"
done

The hosts in the input secrets must still resolve from the new namespace (FQDNs should be used).


Step 3: Known failures and manual recovery

Failure A: Keycloak admin login 400 Bad Request

  • Symptom: a setup job (for example <release>-billing-service-setup-tf-apply) fails with failed to perform initial login to Keycloak ... 400 Bad Request.
  • Cause: the values do not set semarchy-iam.keycloak.auth.existingSecret, so the chart generated a new password while Keycloak still holds the old one. While the release is installed, the old password is in the secrets <release>-semarchy-iam-admin and keycloak-provider (key password) and in the Terraform state tfstate-default-iam-finalize. helm uninstall removes all three; the Keycloak database only stores a hash. After an uninstall or the loss of the cluster, the password only exists in the backup.
  • Action: create the admin secret from the backup, set existingSecret in the values, then run helm upgrade --install again.

Failure B: Realm already exists (409 Conflict)

  • Symptom:<release>-tenant-settings-setup-tf-apply fails with 409 Conflict ... Realm selfhosted already exists.
  • Cause: the Terraform states are missing; the setup jobs do not adopt the existing realm.
  • Data impact: this attempt already deleted the xDM Admin role. After recovery, the role exists again without its mappings: the Keycloak database must be restored or the role reassigned.
  • Action: restore the states from the backup, overwriting the partial ones, release the Terraform locks, then run helm upgrade --install again.
for n in $(jq -r '.items[].metadata.name | select(startswith("tfstate-"))' secrets.json); do
  data=$(jq -r --arg n "$n" '.items[] | select(.metadata.name==$n) | .data.tfstate' secrets.json)
  kubectl get secret "$n" -n "$NS" >/dev/null 2>&1 \
    && kubectl patch secret "$n" -n "$NS" --type merge -p "{\"data\":{\"tfstate\":\"$data\"}}" \
    || jq --arg n "$n" '.items[] | select(.metadata.name==$n)' secrets.json | kubectl apply -n "$NS" -f -
done
kubectl delete lease -n "$NS" $(kubectl get lease -n "$NS" -o name | grep lock-tfstate | cut -d/ -f2)

Failure C: Forbidden on the old namespace

  • Symptom: a setup job fails with ... is forbidden: User "system:serviceaccount:<ns>:..." cannot get resource ... in the namespace "<old-ns>".
  • Cause: the namespace has another name than in the backup and the Terraform states were not rewritten.
  • Action: run the rewrite described in "Restore into a namespace with another name", release the locks, delete the failed pods, then run helm upgrade --install again.
kubectl delete lease -n "$NS" $(kubectl get lease -n "$NS" -o name | grep lock-tfstate | cut -d/ -f2)
kubectl delete pod -n "$NS" --field-selector=status.phase=Failed

Failure D: finalize job stuck in ContainerCreating

  • Symptom: Helm waits until its timeout; the pod <release>-tenant-settings-finalize-keycloak-realms-* shows configmap "<release>-tenant-settings-finalize-realms-config" not found. It happens when the install runs as an upgrade after a failed first attempt.
  • Action: while Helm is still waiting, the ConfigMap is created from the manifest stored in the release; the job then starts and the install goes on.
REV=$(kubectl get secret -n "$NS" -l owner=helm,name="$RELEASE" -o json | jq '[.items[].metadata.labels.version|tonumber]|max')
kubectl get secret "sh.helm.release.v1.${RELEASE}.v${REV}" -n "$NS" -o jsonpath='{.data.release}' |
  base64 -d | base64 -d | gunzip |
  jq -r --arg n "${RELEASE}-tenant-settings-finalize-realms-config" '.hooks[] | select(.name==$n) | .manifest' |
  kubectl apply -n "$NS" -f -

Failure E: an input secret is missing

  • Symptoms, depending on the secret:
    • a pod or setup job stays in CreateContainerConfigError with secret "<name>" not found (for example opensearch-provider for <release>-log-explorer-service-setup-tf-apply);
    • a missing dm-postgres-datasource-<N>: <release>-dm-setup-dm-auto-provisioning fails with Error: Attempt to index null value on data.kubernetes_secret.datasource[...], and Helm stops with failed post-install: resource Job/<ns>/<release>-dm-setup-dm-auto-provisioning not ready.
  • Cause: the secret was not in the backup.
  • Action: restore the secret from the backup or from its source. A pod in CreateContainerConfigError then starts on its own; if Helm already stopped with failed post-install, run helm upgrade --install again.


Step 4: Verify the restore

  1. Every pod is ready: the command below prints nothing.
kubectl get pods -n "$NS" --no-headers | awk '$3!="Completed" {split($2,a,"/"); if (a[1]!=a[2] || $3!="Running") print}'
  1. The realm role mappings match the state before the incident. The query below is run on the Keycloak database before and after, and the counts per role are compared, in particular for xDM Admin.
psql -d keycloak -tAc "SELECT r.name, count(m.user_id) FROM keycloak_role r LEFT JOIN user_role_mapping m ON m.role_id=r.id JOIN realm re ON re.id=r.realm_id WHERE re.name='selfhosted' AND r.client IS NULL GROUP BY r.name ORDER BY 1"
  1. Users can log in and see their Data Management models and data locations.