# services/comms/mas-db-ensure-job.yaml apiVersion: batch/v1 kind: Job metadata: name: mas-db-ensure-4 namespace: comms spec: backoffLimit: 2 template: spec: serviceAccountName: mas-db-ensure restartPolicy: OnFailure volumes: - name: work emptyDir: {} initContainers: - name: prepare image: bitnami/kubectl:latest command: ["/bin/sh", "-c"] args: - | set -euo pipefail umask 077 if kubectl -n postgres get secret postgres-auth >/dev/null 2>&1; then kubectl -n postgres get secret postgres-auth -o jsonpath='{.data.POSTGRES_PASSWORD}' | base64 -d > /work/postgres_password else POSTGRES_PASS="$(kubectl -n postgres get statefulset postgres -o jsonpath='{.spec.template.spec.containers[0].env[?(@.name=="POSTGRES_PASSWORD")].value}')" if [ -z "${POSTGRES_PASS}" ]; then echo "postgres password not found in statefulset env" >&2 exit 1 fi printf '%s' "${POSTGRES_PASS}" > /work/postgres_password kubectl -n postgres create secret generic postgres-auth --from-file=POSTGRES_PASSWORD=/work/postgres_password >/dev/null fi if kubectl -n comms get secret mas-db >/dev/null 2>&1; then kubectl -n comms get secret mas-db -o jsonpath='{.data.password}' | base64 -d > /work/mas_password else head -c 32 /dev/urandom | base64 | tr -d '\n' > /work/mas_password kubectl -n comms create secret generic mas-db --from-file=password=/work/mas_password >/dev/null fi volumeMounts: - name: work mountPath: /work containers: - name: ensure image: postgres:15 env: - name: PGHOST value: postgres-service.postgres.svc.cluster.local - name: PGPORT value: "5432" - name: PGDATABASE value: postgres - name: PGUSER value: postgres command: ["/bin/sh", "-c"] args: - | set -euo pipefail export PGPASSWORD="$(cat /work/postgres_password)" MAS_PASS="$(cat /work/mas_password)" psql -v ON_ERROR_STOP=1 -v mas_pass="${MAS_PASS}" <<'SQL' DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_catalog.pg_roles WHERE rolname = 'mas') THEN EXECUTE format('CREATE ROLE mas LOGIN PASSWORD %L', :mas_pass); ELSE EXECUTE format('ALTER ROLE mas WITH PASSWORD %L', :mas_pass); END IF; END $$; DO $$ BEGIN IF NOT EXISTS (SELECT 1 FROM pg_database WHERE datname = 'mas') THEN CREATE DATABASE mas OWNER mas; END IF; END $$; SQL volumeMounts: - name: work mountPath: /work