apiVersion: v1
kind: Secret
metadata:
  name: keycloak-db-credentials
  namespace: keycloak
type: Opaque
stringData:
  username: keycloak
  password: ${KEYCLOAK_DB_PASSWORD:-change-me}
---
apiVersion: v1
kind: ConfigMap
metadata:
  name: keycloak-db-config
  namespace: keycloak
data:
  POSTGRES_DB: keycloak
  POSTGRES_USER: keycloak
---
apiVersion: apps/v1
kind: StatefulSet
metadata:
  name: keycloak-postgres
  namespace: keycloak
spec:
  serviceName: keycloak-postgres
  replicas: 1
  selector:
    matchLabels:
      app: keycloak-postgres
  template:
    metadata:
      labels:
        app: keycloak-postgres
    spec:
      containers:
      - name: postgres
        image: postgres:15-alpine
        env:
        - name: POSTGRES_DB
          valueFrom:
            configMapKeyRef:
              name: keycloak-db-config
              key: POSTGRES_DB
        - name: POSTGRES_USER
          valueFrom:
            configMapKeyRef:
              name: keycloak-db-config
              key: POSTGRES_USER
        - name: POSTGRES_PASSWORD
          valueFrom:
            secretKeyRef:
              name: keycloak-db-credentials
              key: password
        ports:
        - containerPort: 5432
          name: postgres
        volumeMounts:
        - name: data
          mountPath: /var/lib/postgresql/data
        resources:
          requests:
            memory: "256Mi"
            cpu: "250m"
          limits:
            memory: "512Mi"
            cpu: "500m"
  volumeClaimTemplates:
  - metadata:
      name: data
    spec:
      accessModes: ["ReadWriteOnce"]
      resources:
        requests:
          storage: 10Gi
---
apiVersion: v1
kind: Service
metadata:
  name: keycloak-postgres
  namespace: keycloak
spec:
  selector:
    app: keycloak-postgres
  ports:
  - port: 5432
    targetPort: 5432
    name: postgres
  clusterIP: None

