Files
todo-hetzner/ansible/roles/postgres/tasks/main.yml
T
cole-maxwell1 d118f52387 ops(ansible): harden provisioning and restore automation
Fail before host changes when required deployment variables are missing.

Precreate the PostgreSQL temporary directory and escape Bash syntax during Jinja rendering.
2026-08-07 09:58:15 -05:00

84 lines
2.5 KiB
YAML

---
- name: Create PostgreSQL Ansible temporary directory
ansible.builtin.file:
path: /var/lib/pgsql/.ansible/tmp
state: directory
owner: postgres
group: postgres
mode: "0700"
- name: Initialize PostgreSQL data directory
ansible.builtin.command:
argv: [postgresql-setup, --initdb]
args:
creates: "{{ postgres_data_dir }}/PG_VERSION"
- name: Create canonical PostgreSQL configuration directory
ansible.builtin.file:
path: /etc/todo-postgresql
state: directory
owner: root
group: postgres
mode: "0750"
- name: Render canonical PostgreSQL server configuration
ansible.builtin.template:
src: postgresql.conf.j2
dest: /etc/todo-postgresql/postgresql.conf
owner: root
group: postgres
mode: "0640"
notify: Restart PostgreSQL
- name: Render canonical PostgreSQL client authentication
ansible.builtin.template:
src: pg_hba.conf.j2
dest: /etc/todo-postgresql/pg_hba.conf
owner: root
group: postgres
mode: "0640"
notify: Restart PostgreSQL
- name: Install PostgreSQL configuration in data directory
ansible.builtin.copy:
src: "/etc/todo-postgresql/{{ item }}"
dest: "{{ postgres_data_dir }}/{{ item }}"
remote_src: true
owner: postgres
group: postgres
mode: "0600"
loop:
- postgresql.conf
- pg_hba.conf
notify: Restart PostgreSQL
- name: Start PostgreSQL
ansible.builtin.systemd_service:
name: "{{ postgres_service }}"
enabled: true
state: started
- name: Apply PostgreSQL configuration before provisioning
ansible.builtin.meta: flush_handlers
- name: Provision application database role
ansible.builtin.command:
argv: [psql, --set, "role={{ app_db_user }}", --set, "password={{ app_db_password }}", --dbname, postgres]
stdin: |
SELECT format('CREATE ROLE %I LOGIN PASSWORD %L', :'role', :'password')
WHERE NOT EXISTS (SELECT FROM pg_roles WHERE rolname = :'role') \gexec
SELECT format('ALTER ROLE %I LOGIN PASSWORD %L', :'role', :'password') \gexec
become_user: postgres
changed_when: false
no_log: true
- name: Provision application database
ansible.builtin.command:
argv: [psql, --set, "database={{ app_db_name }}", --set, "role={{ app_db_user }}", --dbname, postgres]
stdin: |
SELECT format('CREATE DATABASE %I OWNER %I', :'database', :'role')
WHERE NOT EXISTS (SELECT FROM pg_database WHERE datname = :'database') \gexec
SELECT format('ALTER DATABASE %I OWNER TO %I', :'database', :'role') \gexec
become_user: postgres
changed_when: false