apiVersion: v1 kind: ConfigMap metadata: name: arschrock-postgresql-backup namespace: backup data: backup.sh: | #!/bin/sh set -eu backup_fs=$(stat -f -c %T /backup) echo "Backup filesystem: $backup_fs" test "$backup_fs" = bcachefs test -d /backup/kubernetes/postgresql/arschrock test "$(stat -c %u /backup/kubernetes/postgresql/arschrock)" = 962 test -S /postgresql/.s.PGSQL.5432 export PGHOST=/postgresql PGUSER=postgres PGDATABASE=postgres destination="/backup/kubernetes/postgresql/arschrock/$(date -u +%Y-%m-%dT%H-%M-%SZ)" mkdir -m 0700 "$destination" pg_dumpall --globals-only --no-role-passwords > "$destination/globals.sql.partial" test -s "$destination/globals.sql.partial" mv "$destination/globals.sql.partial" "$destination/globals.sql" psql -AtX -v ON_ERROR_STOP=1 -c 'SELECT datname FROM pg_database WHERE datallowconn AND NOT datistemplate ORDER BY datname' > "$destination/databases.list" while IFS= read -r database; do case "$database" in *[!a-zA-Z0-9_-]*|'') echo "Unsafe database name: $database" >&2; exit 1 ;; esac pg_dump --format=custom --file="$destination/$database.dump.partial" --dbname="$database" pg_restore --list "$destination/$database.dump.partial" >/dev/null mv "$destination/$database.dump.partial" "$destination/$database.dump" done < "$destination/databases.list" test "$(find "$destination" -maxdepth 1 -name '*.dump' | wc -l)" -gt 0 date -u +%FT%TZ > "$destination/complete" echo "Completed PostgreSQL backup at $destination" --- apiVersion: batch/v1 kind: CronJob metadata: name: arschrock-postgresql-backup namespace: backup spec: schedule: "15 2 * * *" timeZone: Europe/Vienna concurrencyPolicy: Forbid startingDeadlineSeconds: 3600 successfulJobsHistoryLimit: 7 failedJobsHistoryLimit: 7 jobTemplate: spec: backoffLimit: 0 activeDeadlineSeconds: 14400 template: spec: nodeSelector: kubernetes.io/hostname: arschrock tolerations: - key: node-role.kubernetes.io/control-plane operator: Exists effect: NoSchedule automountServiceAccountToken: false restartPolicy: Never securityContext: runAsUser: 962 runAsGroup: 962 containers: - name: pg-dump image: postgres:18.6 imagePullPolicy: IfNotPresent command: [/bin/sh, /scripts/backup.sh] securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true capabilities: drop: [ALL] volumeMounts: - name: backup mountPath: /backup - name: postgresql-socket mountPath: /postgresql readOnly: true - name: scripts mountPath: /scripts readOnly: true volumes: - name: backup hostPath: path: /mnt/backup type: Directory - name: postgresql-socket hostPath: path: /run/postgresql type: Directory - name: scripts configMap: name: arschrock-postgresql-backup defaultMode: 0555