Update postgres bootstrap allowing multiple databases

This commit is contained in:
IamTheFij 2023-07-25 16:40:35 -07:00
parent ac29343d96
commit 0ea9da3a53
2 changed files with 17 additions and 6 deletions

View File

@ -265,19 +265,23 @@ SELECT 'NOOP';
template {
data = <<EOF
{{ with nomadVar "nomad/jobs/${name}" -}}
/usr/bin/createdb {{ .${postgres_bootstrap.db_name_key} }}
{{ end }}
/usr/bin/psql -X -f $${NOMAD_SECRETS_DIR/bootstrap.sql
%{ if length(postgres_bootstrap.databases) > 0 }
%{ for db_name in postgres_bootstrap.databases ~}
/usr/bin/createdb ${db_name}
%{ endfor }
%{ else }
{{ with nomadVar "nomad/jobs/${name}" }}/usr/bin/createdb {{ .${postgres_bootstrap.db_name_key} }}{{ end }}
%{ endif }
/usr/bin/psql -X -f $${NOMAD_SECRETS_DIR}/bootstrap.sql
EOF
destination = "$${NOMAD_TASK_DIR}/boostrap.sh"
destination = "$${NOMAD_TASK_DIR}/bootstrap.sh"
}
template {
data = <<EOF
PGHOSTADDR=127.0.0.1
PGPORT=5432
{{ with nomadVar "nomad/jobs/${name}/${name}/bootstrap" }}
{{ with nomadVar "nomad/jobs/${name}/${name}/postgres-bootstrap" }}
PGUSER={{ .superuser }}
# TODO: Passfile?
PGPASSWORD={{ .superuser_pass }}
@ -293,7 +297,13 @@ PGPASSWORD={{ .superuser_pass }}
DO $$
BEGIN
CREATE ROLE {{ .${postgres_bootstrap.db_user_key} }} LOGIN PASSWORD '{{ .${postgres_bootstrap.db_pass_key} }}';
%{ if length(postgres_bootstrap.databases) > 0 }
%{ for db_name in postgres_bootstrap.databases }
GRANT ALL ON DATABASE "${db_name}" TO {{ .${postgres_bootstrap.db_user_key} }};
%{ endfor }
%{ else }
GRANT ALL ON DATABASE "{{ .${postgres_bootstrap.db_name_key} }}" TO {{ .${postgres_bootstrap.db_user_key} }};
%{ endif }
EXCEPTION WHEN duplicate_object THEN RAISE NOTICE '%, skipping', SQLERRM USING ERRCODE = SQLSTATE;
END
$$;

View File

@ -188,6 +188,7 @@ variable "postgres_bootstrap" {
db_name_key = optional(string, "db_name")
db_user_key = optional(string, "db_user")
db_pass_key = optional(string, "db_pass")
databases = optional(list(string), [])
})
default = null