{{- $existingSecret := lookup "v1" "Secret" .Release.Namespace (printf "%s-credentials" .Release.Name) }} {{- $passwords := dict }} {{- with (index $existingSecret "data") }} {{- range $k, $v := . }} {{- $_ := set $passwords $k (b64dec $v) }} {{- end }} {{- end }} {{- range $user, $u := .Values.users }} {{- if $u.password }} {{- $_ := set $passwords $user $u.password }} {{- else if not (index $passwords $user) }} {{- $_ := set $passwords $user (randAlphaNum 16) }} {{- end }} {{- end }} {{- if .Values.users }} apiVersion: v1 kind: Secret metadata: name: {{ .Release.Name }}-credentials stringData: {{- range $user, $u := .Values.users }} {{ quote $user }}: {{ quote (index $passwords $user) }} {{- end }} {{- end }} --- apiVersion: v1 kind: Secret metadata: name: {{ .Release.Name }}-init-script stringData: init.sh: | #!/bin/bash set -e until pg_isready ; do sleep 5; done echo "== create users" {{- if and .Values.users (not (hasKey .Values.users "postgres")) }} psql -v ON_ERROR_STOP=1 <<\EOT {{- range $user, $u := .Values.users }} SELECT 'CREATE ROLE "{{ $user }}" LOGIN INHERIT;' WHERE NOT EXISTS (SELECT FROM pg_catalog.pg_roles WHERE rolname = '{{ $user }}')\gexec ALTER ROLE "{{ $user }}" WITH PASSWORD '{{ index $passwords $user }}' LOGIN INHERIT {{ ternary "REPLICATION" "NOREPLICATION" (default false $u.replication) }}; COMMENT ON ROLE "{{ $user }}" IS 'user managed by helm'; {{- end }} EOT {{- else if and .Values.users (hasKey .Values.users "postgres") }} {{- fail "`users.postgres` is forbidden by policy. Use a different username." }} {{- end }} echo "== delete users" MANAGED_USERS=$(echo '\du+' | psql | awk -F'|' '$4 == " user managed by helm" {print $1}' | awk NF=NF RS= OFS=' ') DEFINED_USERS="{{ join " " (keys .Values.users) }}" DELETE_USERS=$(for user in $MANAGED_USERS; do case " $DEFINED_USERS " in *" $user "*) :;; *) echo $user;; esac; done) echo "users to delete: $DELETE_USERS" for user in $DELETE_USERS; do # https://stackoverflow.com/a/51257346/2931267 psql -v ON_ERROR_STOP=1 --echo-all <