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

View File

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