description: 'The ansible role I use to manage my PostgreSQL databases'
date: '2024-10-09'
tags:
- ansible
- PostgreSQL
---
## Introduction
Before succumbing to nixos, I had been using an ansible role to manage my PostgreSQL databases. Now that I am in need of it again I refined it a bit: here is the result.
## The role
### Tasks
My `main.yaml` relies on OS specific tasks:
``` yaml
---
- name: 'Generate postgres user password'
include_tasks: 'generate_password.yaml'
vars:
name: 'postgres'
when: '(ansible_local["postgresql_postgres"]|default({})).password is undefined'
- name: 'Run OS tasks'
include_tasks: '{{ ansible_distribution }}.yaml'
- name: 'Start postgresql and activate it on boot'
service:
name: 'postgresql'
enabled: true
state: 'started'
```
Here is an example in `Debian.yaml`:
``` yaml
---
- name: 'Install postgresql'
package:
name:
- 'postgresql'
- 'python3-psycopg2' # necessary for the ansible postgresql modules
- name: 'Configure postgresql'
template:
src: 'pg_hba.conf'
dest: '/etc/postgresql/15/main/'
owner: 'root'
group: 'postgres'
mode: '0440'
notify: 'reload postgresql'
- name: 'Configure postgresql (file that require a restart when modified)'
template:
src: 'postgresql.conf'
dest: '/etc/postgresql/15/main/'
owner: 'root'
group: 'postgres'
mode: '0440'
notify: 'restart postgresql'
- meta: 'flush_handlers'
- name: 'Set postgres admin password'
shell:
cmd: "printf \"ALTER USER postgres WITH PASSWORD '%s';\" \"{{ ansible_local.postgresql_postgres.password }}\" | su -c psql - postgres"
when: 'postgresql_password_postgres is defined'
```
My `generate_password.yaml` will persist a password with a custom fact:
I do not call the role from a playbook, I prefer running the setup from an application's role that relies on postgresql using a `meta/main.yaml` containing something like: