Skip to main content

CloudNativePG

Install the CloudNativePG kubectl plugin.

apiVersion: postgresql.cnpg.io/v1
kind: Cluster
metadata:
name: keycloak-pg
namespace: keycloak
spec:
instances: 1
imageName: ghcr.io/cloudnative-pg/postgresql:17
storage:
size: 8Gi
walStorage:
size: 8Gi

affinity:
nodeAffinity:
preferredDuringSchedulingIgnoredDuringExecution:
- weight: 100
preference:
matchExpressions:
- key: topology.kubernetes.io/zone
operator: In
values:
- udl

# LIVE MIGRATION CONFIGURATION

bootstrap:
initdb:
import:
type: microservice
schemaOnly: true
databases:
- bitnami-keycloak
source:
externalCluster: keycloak-old

externalClusters:
- name: keycloak-old
connectionParameters:
host: keycloak-postgresql.keycloak.svc.cluster.local
port: '5432'
user: postgres
dbname: postgres
password:
name: keycloak-auth
key: postgres-password

# BACKUP CONFIGURATION

# backup:
# retentionPolicy: 15d
# barmanObjectStore:
# destinationPath: "gs://agrospai-cnpg-backup"
# googleCredentials:
# applicationCredentials:
# name: backup-creds
# key: gcsCredentials
# data:
# compression: bzip2
# wal:
# compression: bzip2

# RECOVERY CONFIGURATION (migration)

# bootstrap:
# recovery:
# source: umami-pg

# externalClusters:
# - name: umami-pg
# barmanObjectStore:
# destinationPath: "gs://agrospai-cnpg-backup"
# googleCredentials:
# applicationCredentials:
# name: backup-creds
# key: gcsCredentials
# wal:
# maxParallel: 8

# RECOVERY CONFIGURATION (local)

# bootstrap:
# recovery:
# backup:
# name: umami-backup
kubectl cnpg publication create keycloak-pg \
--external-cluster keycloak-old \
--dbname bitnami_keycloak \
--publication migration_pub \
--namespace keycloak \
--all-tables
kubectl cnpg subscription create keycloak-pg \
--external-cluster keycloak-old \
--publication migration_pub \
--namespace keycloak \
--publication-dbname bitnami_keycloak \
--subscription migration_sub
kubectl cnpg subscription sync-sequences \
--subscription migration_sub \
--dbname app \
--namespace keycloak \
keycloak-pg

Check all tables are synced in new database:

SELECT
srrelid::regclass AS table,
srsubstate
FROM pg_subscription_rel;
CodeMeaning
iinitializing
ddata is being copied
ffinished table copy
rready (fully synced & replicating)

Verify no replication lag:

SELECT now() - latest_end_time AS replication_delay
FROM pg_stat_subscription;

It should be close to 0 seconds.

Change application connection string to point to new database

Cleanup old publication and subscription:

kubectl cnpg subscription drop keycloak-pg --subscription migration_sub --namespace keycloak --dbname app
kubectl cnpg publication drop keycloak-pg --publication migration_pub --namespace keycloak --dbname bitnami_keycloak --external-cluster keycloak-old

Remove old database if no longer needed.