From ad3a53bed7f4cdb7179a59c9b0998684a4a36284 Mon Sep 17 00:00:00 2001 From: Robert Kaussow Date: Tue, 13 Aug 2024 09:32:28 +0200 Subject: [PATCH] add initdb script --- defaults/main.yml | 4 ++++ files/init-user-db.sh | 10 ++++++++++ tasks/main.yml | 9 +++++++++ templates/etc/containers/systemd/postgres.container.j2 | 4 ++-- 4 files changed, 25 insertions(+), 2 deletions(-) create mode 100644 files/init-user-db.sh diff --git a/defaults/main.yml b/defaults/main.yml index de277b7..0d29ff9 100644 --- a/defaults/main.yml +++ b/defaults/main.yml @@ -1,5 +1,7 @@ --- postgres_image: "docker.io/library/postgres:latest" +postgres_uid: 999 +postgres_gid: 999 # @var postgres_volumes:description: > Define required docker volumes. # @end @@ -11,6 +13,8 @@ postgres_image: "docker.io/library/postgres:latest" # type: volume # @end postgres_volumes: + - name: "postgres-initdb" + dest: "/docker-entrypoint-initdb.d" - name: "postgres-data" dest: /var/lib/postgresql/data diff --git a/files/init-user-db.sh b/files/init-user-db.sh new file mode 100644 index 0000000..f80db1f --- /dev/null +++ b/files/init-user-db.sh @@ -0,0 +1,10 @@ +#!/usr/bin/env sh +set -e + +if [ -n "$POSTGRES_APP_USER" ]; then + psql -v ON_ERROR_STOP=1 --username "${POSTGRES_USER:-postgres}" --dbname "$" <<-EOSQL + CREATE USER $POSTGRES_APP_USER with encrypted password '$POSTGRES_APP_PASSWORD'; + GRANT CREATE, CONNECT ON DATABASE ${POSTGRES_DB:-postgres} TO $POSTGRES_APP_USER; + ALTER DEFAULT PRIVILEGES IN SCHEMA public GRANT SELECT, UPDATE, INSERT, DELETE, REFERENCES ON TABLES TO $POSTGRES_APP_USER; +EOSQL +fi diff --git a/tasks/main.yml b/tasks/main.yml index 0ea98af..d6efdf1 100644 --- a/tasks/main.yml +++ b/tasks/main.yml @@ -46,6 +46,15 @@ mode: "0640" notify: __postgres_restart + - name: Deploy init-user-db + ansible.builtin.copy: + src: init-user-db.sh + dest: "{{ __postgres_volumes_map['postgres-initdb'] }}" + owner: "{{ postgres_uid }}" + group: "{{ postgres_gid }}" + mode: "0644" + when: "'postgres-initdb' in __postgres_volumes_map" + - name: Ensure service state systemd: name: "postgres.service" diff --git a/templates/etc/containers/systemd/postgres.container.j2 b/templates/etc/containers/systemd/postgres.container.j2 index 39d6ad3..2aa1bb6 100644 --- a/templates/etc/containers/systemd/postgres.container.j2 +++ b/templates/etc/containers/systemd/postgres.container.j2 @@ -13,8 +13,8 @@ EnvironmentFile=/etc/containers/systemd/postgres.sys.env Image={{ postgres_image }} Exec=postgres $POSTGRES_ARGS EnvironmentFile=/etc/containers/systemd/postgres.env -User=999 -Group=999 +User={{ postgres_uid }} +Group={{ postgres_gid }} {% for item in postgres_volumes %} Volume={{ item.name }}:{{ item.dest }}{{ ":" + item.opts if item.opts is defined else "" }} {% endfor %}