Ansible Automation Playbook Creator
Generates production-ready, idempotent Ansible playbooks and roles for any infrastructure automation or configuration task.
Example run
Generated by Claude Opus 5.5 on November 25, 2026
Inputs used
- Infrastructure task
- Install and configure PostgreSQL 16 on a single dedicated database server for a billing service. Add the official PostgreSQL APT repository (apt.postgresql.org, Ubuntu 22.04 "jammy" codename) and install the `postgresql-16` and `postgresql-contrib` packages, pinned to the PGDG repo. Leave the data directory at its default path /var/lib/postgresql/16/main. Configure postgresql.conf so the server listens on 0.0.0.0 port 5432, with max_connections=100 and shared_buffers=256MB. Configure pg_hba.conf to permit md5-authenticated TCP connections only from the internal application subnet 10.20.30.0/24 plus the local Unix socket/localhost, rejecting all other remote hosts. Create a database named `billing_app` and a login role `billing_svc` (password supplied via an Ansible Vault variable `vault_billing_svc_password`) that is granted all privileges on that database only, with no superuser rights. Open TCP/5432 in UFW restricted to the 10.20.30.0/24 subnet, while keeping UFW's default-deny posture for everything else (and still allowing SSH on port 22 from anywhere so management access isn't locked out). Ensure the `postgresql` systemd service is enabled and running, with the service automatically restarted whenever postgresql.conf or pg_hba.conf changes. Set up a nightly cron job at 02:30 server time, run as the `postgres` OS user, that performs `pg_dump` of `billing_app` into /var/backups/postgresql/billing_app_YYYYMMDD.sql.gz and prunes any backup files older than 14 days.
- Inventory group
- db_servers
- Target OS
- Ubuntu 22.04 LTS (Jammy Jellyfish), x86_64
- Environment
- production
- Constraints
- The automation user is `deploy`, who already has an SSH keypair provisioned on the target and a sudoers entry at /etc/sudoers.d/deploy granting `NOPASSWD: ALL` — nothing restricts which modules, packages, or shell commands Ansible may run. The target host has unrestricted outbound internet access to the standard Ubuntu archive mirrors and to apt.postgresql.org (no corporate proxy, no mirror pinning required). This is a brand-new VM with no prior PostgreSQL installation, so no data migration or in-place upgrade logic is needed. UFW is already installed (from the base image) but currently inactive/unconfigured. The Ansible control node has Python 3.10+, ansible-core 2.16, and can install the `community.postgresql` and `community.general` collections via ansible-galaxy. A Vault password file is kept at ~/.vault_pass.txt on the control node and is already in .gitignore. This is a single standalone database host — no replication, clustering, external load balancer, or TLS certificate issuance across multiple nodes is in scope.
PostgreSQL 16 for the Billing Service: Ansible Role
Your spec was complete enough to build from. While designing it I found one real conflict and made four judgment calls. Each is a single variable you can change.
⚠️ Decisions to review before running
| # | Topic | What I did and why |
|---|---|---|
| 1 | postgresql-contrib package (conflicts with the spec) |
In PGDG, postgresql-contrib is a metapackage that depends on the newest major version (17 or 18 today). Installing it would pull in a second server and create a second cluster on port 5433. Since PostgreSQL 10, contrib modules ship inside postgresql-16 itself. The role installs postgresql-16, asserts the contrib extensions exist, and adds an APT pin that blocks other major versions. If you really need the metapackage, tell me and I'll rework the pin. |
| 2 | Password hashing | I left password_encryption = scram-sha-256 (the PG16 default). pg_hba.conf uses md5 as you asked. PostgreSQL automatically uses SCRAM when the stored hash is SCRAM, so md5-method clients still work, and you avoid weak MD5 hashes (deprecated in PG18). |
| 3 | Remote pg_hba rule |
Remote access from 10.20.30.0/24 is narrowed to billing_app/billing_svc only, not all all. You can widen it with postgresql_hba_app_rules. |
| 4 | Local socket | local connections use peer, the Debian default. The postgres-run cron backup depends on it. |
| 5 | Schema rights | On PG15+, GRANT ALL ON DATABASE does not let the app create tables in public. The role also grants ALL ON SCHEMA public inside billing_app (toggle: postgresql_app_grant_public_schema). It revokes CONNECT/TEMP on billing_app from PUBLIC. |
1. Plan
- Preflight: assert Ubuntu 22.04 x86_64, enough RAM, a Vault password present (≥16 chars), and that Ansible connects on the SSH port UFW will allow (lockout guard).
- Repository: download the PGDG key into
/etc/apt/keyrings, verify its fingerprint, add an APT pin that prefers PGDG and blocks other majors, then add thejammy-pgdgrepo withsigned-by. - Install:
postgresql-16,postgresql-client-16,python3-psycopg2,acl,cron. Then assert that exactly one cluster (16/main) exists at/var/lib/postgresql/16/mainand that contrib is present. - Configure: edit
postgresql.confin place and templatepg_hba.conf, keeping timestamped backups. Validate both files against the running server before any restart. Then the handler restartspostgresql@16-mainand waits for the port. - Database: create the
billing_svcrole (LOGIN, no superuser/createdb/createrole/replication/bypassrls), thebilling_appdatabase, and the grants. - Firewall: allow SSH/22 from anywhere and 5432/tcp from
10.20.30.0/24only. Set default deny incoming and routed, allow outgoing, then enable UFW. Rules are added before enabling. - Backup: install an atomic dump script (root-owned, executable by
postgres) and a cron entry at 02:30 aspostgres. Old dumps are pruned only after a successful dump. - Verify: check effective settings, the listening socket, role flags, and a TCP password login as
billing_svc.
Guaranteed end state: PG16 from PGDG is listening on 0.0.0.0:5432 with the specified settings. Only the app subnet and localhost can authenticate, and UFW enforces the same boundary. Nightly compressed dumps are kept for 14 days. A second run reports changed=0.
2. Project layout
postgres-billing/
├── ansible.cfg
├── inventory.ini
├── requirements.yml
├── site.yml
├── group_vars/
│ └── db_servers/
│ ├── vars.yml
│ └── vault.yml # ansible-vault encrypted
└── roles/
└── postgresql/
├── defaults/main.yml
├── handlers/main.yml
├── meta/main.yml
├── tasks/
│ ├── main.yml
│ ├── preflight.yml
│ ├── repo.yml
│ ├── install.yml
│ ├── configure.yml
│ ├── database.yml
│ ├── firewall.yml
│ ├── backup.yml
│ └── verify.yml
└── templates/
├── pgdg.pref.j2
├── pg_hba.conf.j2
└── pg_backup.sh.j2
ansible.cfg
Pipelining is required so that become_user: postgres works cleanly. The role also installs acl as a fallback.
[defaults]
inventory = inventory.ini
remote_user = deploy
vault_password_file = ~/.vault_pass.txt
roles_path = ./roles
interpreter_python = /usr/bin/python3
host_key_checking = True
retry_files_enabled = False
callback_result_format = yaml
[privilege_escalation]
become = False
become_method = sudo
[ssh_connection]
pipelining = True
requirements.yml
The version ranges are compatible with ansible-core 2.16. Newer major versions of both collections drop 2.16 support. Note that ansible-core 2.16 itself is end-of-life, so plan an upgrade.
---
collections:
- name: community.postgresql
version: ">=3.4.0,<4.0.0"
- name: community.general
version: ">=8.0.0,<12.0.0"
site.yml
---
- name: Provision PostgreSQL 16 for the billing service
hosts: db_servers
become: true
gather_facts: true
roles:
- role: postgresql
3. Role
roles/postgresql/defaults/main.yml
---
# ---------- Version / layout (Debian/Ubuntu postgresql-common conventions) ----------
postgresql_version: "16"
postgresql_cluster_name: main
postgresql_data_dir: "/var/lib/postgresql/{{ postgresql_version }}/{{ postgresql_cluster_name }}"
postgresql_config_dir: "/etc/postgresql/{{ postgresql_version }}/{{ postgresql_cluster_name }}"
postgresql_bin_dir: "/usr/lib/postgresql/{{ postgresql_version }}/bin"
postgresql_service_name: postgresql # wrapper unit
postgresql_cluster_unit: "postgresql@{{ postgresql_version }}-{{ postgresql_cluster_name }}" # real server unit
# ---------- PGDG repository ----------
postgresql_pgdg_repo_url: https://apt.postgresql.org/pub/repos/apt
postgresql_pgdg_codename: jammy
postgresql_pgdg_key_url: https://www.postgresql.org/media/keys/ACCC4CF8.asc
postgresql_pgdg_key_path: /etc/apt/keyrings/postgresql.asc
postgresql_pgdg_key_fingerprint: B97B0AFCAA1A47F044F244A07FCC7D46ACCC4CF8
postgresql_pgdg_pin_priority: 900
postgresql_pgdg_pinned_packages:
- "postgresql-{{ postgresql_version }}"
- "postgresql-client-{{ postgresql_version }}"
- postgresql-common
- postgresql-client-common
- libpq5
# Blocks server/client majors 17-99 so no metapackage can install a second cluster.
# Update this if you change postgresql_version.
postgresql_pgdg_blocked_regex: '/^postgresql-(client-)?(1[7-9]|[2-9][0-9])$/'
# ---------- Packages ----------
# Contrib modules are shipped inside postgresql-16 (asserted in install.yml).
postgresql_packages:
- "postgresql-{{ postgresql_version }}"
- "postgresql-client-{{ postgresql_version }}"
- python3-psycopg2 # required by community.postgresql modules
- acl # safe become_user to unprivileged 'postgres'
- cron
# ---------- postgresql.conf ----------
postgresql_listen_addresses: "0.0.0.0"
postgresql_port: 5432
postgresql_max_connections: 100
postgresql_shared_buffers: "256MB"
postgresql_password_encryption: scram-sha-256
postgresql_conf_settings:
listen_addresses: "'{{ postgresql_listen_addresses }}'"
port: "{{ postgresql_port }}"
max_connections: "{{ postgresql_max_connections }}"
shared_buffers: "{{ postgresql_shared_buffers }}"
password_encryption: "{{ postgresql_password_encryption }}"
# Optional extra settings, e.g. { log_connections: "on", log_disconnections: "on" }
postgresql_conf_extra_settings: {}
postgresql_min_memory_mb: 1024
# ---------- Application DB / role ----------
postgresql_app_db_name: billing_app
postgresql_app_db_user: billing_svc
postgresql_app_db_password: "{{ vault_billing_svc_password | default('') }}"
postgresql_app_db_encoding: UTF8
postgresql_app_db_locale: C.UTF-8
postgresql_app_subnet: 10.20.30.0/24
postgresql_app_grant_public_schema: true
postgresql_app_revoke_public_connect: true
# ---------- pg_hba.conf ----------
postgresql_hba_auth_method: md5
postgresql_hba_app_rules:
- database: "{{ postgresql_app_db_name }}"
user: "{{ postgresql_app_db_user }}"
address: "{{ postgresql_app_subnet }}"
# ---------- Firewall (UFW) ----------
postgresql_ufw_ssh_port: 22
postgresql_ufw_ssh_rule: allow # 'limit' adds brute-force rate limiting
postgresql_ufw_logging: low
# ---------- Backups ----------
postgresql_backup_dir: /var/backups/postgresql
postgresql_backup_script: "/usr/local/bin/pg_backup_{{ postgresql_app_db_name }}.sh"
postgresql_backup_retention_days: 14
postgresql_backup_cron_minute: "30"
postgresql_backup_cron_hour: "2"
# Internal: set in preflight
postgresql_check_mode_fresh_host: false
roles/postgresql/meta/main.yml
---
galaxy_info:
author: platform-team
description: PostgreSQL 16 (PGDG) single-node server for the billing service
license: MIT
min_ansible_version: "2.16"
platforms:
- name: Ubuntu
versions:
- jammy
dependencies: []
roles/postgresql/handlers/main.yml
The handlers restart the cluster instance unit. postgresql.service is a oneshot wrapper that can report success even when the cluster fails to start.
---
- name: Restart PostgreSQL cluster
ansible.builtin.systemd_service:
name: "{{ postgresql_cluster_unit }}"
state: restarted
listen: restart postgresql
- name: Wait for PostgreSQL to accept TCP connections
ansible.builtin.wait_for:
host: 127.0.0.1
port: "{{ postgresql_port }}"
timeout: 60
listen: restart postgresql
roles/postgresql/tasks/main.yml
---
- name: Run preflight checks
ansible.builtin.import_tasks: preflight.yml
tags: [always]
- name: Configure the PGDG APT repository
ansible.builtin.import_tasks: repo.yml
tags: [postgresql, repo]
- name: Install PostgreSQL packages
ansible.builtin.import_tasks: install.yml
tags: [postgresql, install]
- name: Configure postgresql.conf and pg_hba.conf
ansible.builtin.import_tasks: configure.yml
when: not (postgresql_check_mode_fresh_host | bool)
tags: [postgresql, config]
- name: Apply pending PostgreSQL restarts before touching databases
ansible.builtin.meta: flush_handlers
tags: [postgresql, config, database]
- name: Create the application database, role and grants
ansible.builtin.import_tasks: database.yml
when: not (postgresql_check_mode_fresh_host | bool)
tags: [postgresql, database]
- name: Configure UFW
ansible.builtin.import_tasks: firewall.yml
tags: [firewall]
- name: Configure nightly backups
ansible.builtin.import_tasks: backup.yml
when: not (postgresql_check_mode_fresh_host | bool)
tags: [backup]
- name: Verify the final state
ansible.builtin.import_tasks: verify.yml
when: not (postgresql_check_mode_fresh_host | bool)
tags: [verify]
roles/postgresql/tasks/preflight.yml
---
- name: Assert supported platform (Ubuntu 22.04 x86_64)
ansible.builtin.assert:
that:
- ansible_facts['distribution'] == 'Ubuntu'
- ansible_facts['distribution_release'] == postgresql_pgdg_codename
- ansible_facts['architecture'] == 'x86_64'
fail_msg: >-
Unsupported platform {{ ansible_facts['distribution'] }}
{{ ansible_facts['distribution_version'] }} ({{ ansible_facts['architecture'] }}).
This role targets Ubuntu 22.04 (jammy) x86_64.
quiet: true
- name: Assert enough RAM for shared_buffers={{ postgresql_shared_buffers }}
ansible.builtin.assert:
that:
- ansible_facts['memtotal_mb'] | int >= postgresql_min_memory_mb | int
fail_msg: "Host has {{ ansible_facts['memtotal_mb'] }} MB RAM; at least {{ postgresql_min_memory_mb }} MB expected."
quiet: true
- name: Assert the application role password is supplied via Ansible Vault
ansible.builtin.assert:
that:
- postgresql_app_db_password | length >= 16
fail_msg: >-
vault_billing_svc_password is undefined or shorter than 16 characters.
Define it in group_vars/db_servers/vault.yml (ansible-vault encrypted).
quiet: true
- name: Assert the application subnet looks like an IPv4 CIDR
ansible.builtin.assert:
that:
- postgresql_app_subnet is match('^\d{1,3}(\.\d{1,3}){3}/\d{1,2}$')
quiet: true
- name: Assert Ansible connects on the SSH port UFW will allow (lockout guard)
ansible.builtin.assert:
that:
- (ansible_port | default(22)) | int == postgresql_ufw_ssh_port | int
fail_msg: >-
Ansible connects on port {{ ansible_port | default(22) }} but UFW will only
allow SSH on {{ postgresql_ufw_ssh_port }}. Refusing to continue.
quiet: true
- name: Check whether the PostgreSQL {{ postgresql_version }} server binary exists
ansible.builtin.stat:
path: "{{ postgresql_bin_dir }}/postgres"
register: postgresql_reg_server_binary
- name: Flag check-mode runs against a host without PostgreSQL installed
ansible.builtin.set_fact:
postgresql_check_mode_fresh_host: "{{ ansible_check_mode and not postgresql_reg_server_binary.stat.exists }}"
- name: Warn that post-install stages are skipped in this dry run
ansible.builtin.debug:
msg: >-
Check mode on a host without PostgreSQL {{ postgresql_version }}: config, database,
backup and verify stages are skipped because they depend on installed packages.
when: postgresql_check_mode_fresh_host | bool
roles/postgresql/tasks/repo.yml
---
- name: Install APT repository prerequisites
ansible.builtin.apt:
name:
- ca-certificates
- gnupg
state: present
update_cache: true
cache_valid_time: 3600
- name: Ensure /etc/apt/keyrings exists
ansible.builtin.file:
path: /etc/apt/keyrings
state: directory
owner: root
group: root
mode: "0755"
- name: Download the PGDG repository signing key
ansible.builtin.get_url:
url: "{{ postgresql_pgdg_key_url }}"
dest: "{{ postgresql_pgdg_key_path }}"
owner: root
group: root
mode: "0644"
force: false
- name: Stat the PGDG signing key
ansible.builtin.stat:
path: "{{ postgresql_pgdg_key_path }}"
register: postgresql_reg_pgdg_key
- name: Read the PGDG signing key fingerprint
ansible.builtin.command:
argv:
- gpg
- --batch
- --show-keys
- --with-colons
- --with-fingerprint
- "{{ postgresql_pgdg_key_path }}"
register: postgresql_reg_pgdg_key_info
changed_when: false
check_mode: false
when: postgresql_reg_pgdg_key.stat.exists
- name: Verify the PGDG signing key fingerprint
ansible.builtin.assert:
that:
- postgresql_pgdg_key_fingerprint in postgresql_reg_pgdg_key_info.stdout
fail_msg: >-
{{ postgresql_pgdg_key_path }} does not have fingerprint {{ postgresql_pgdg_key_fingerprint }}.
Delete it and investigate before re-running.
quiet: true
when: postgresql_reg_pgdg_key.stat.exists
- name: Pin PostgreSQL packages to PGDG and block other major versions
ansible.builtin.template:
src: pgdg.pref.j2
dest: /etc/apt/preferences.d/pgdg.pref
owner: root
group: root
mode: "0644"
- name: Add the PGDG APT repository
ansible.builtin.apt_repository:
repo: >-
deb [arch=amd64 signed-by={{ postgresql_pgdg_key_path }}]
{{ postgresql_pgdg_repo_url }} {{ postgresql_pgdg_codename }}-pgdg main
filename: pgdg
state: present
update_cache: true
roles/postgresql/templates/pgdg.pref.j2
# {{ ansible_managed }}
Explanation: Prefer PGDG (apt.postgresql.org) for PostgreSQL {{ postgresql_version }} packages
Package: {{ postgresql_pgdg_pinned_packages | join(' ') }}
Pin: release o=apt.postgresql.org
Pin-Priority: {{ postgresql_pgdg_pin_priority }}
Explanation: Never install another PostgreSQL major version (prevents a second cluster)
Package: {{ postgresql_pgdg_blocked_regex }}
Pin: version *
Pin-Priority: -1
roles/postgresql/tasks/install.yml
---
- name: Install PostgreSQL {{ postgresql_version }} and supporting packages
ansible.builtin.apt:
name: "{{ postgresql_packages }}"
state: present
update_cache: true
cache_valid_time: 3600
- name: Validate the installation and ensure services are running
when: not (postgresql_check_mode_fresh_host | bool)
block:
- name: Check that the default cluster data directory is initialised
ansible.builtin.stat:
path: "{{ postgresql_data_dir }}/PG_VERSION"
register: postgresql_reg_pg_version
- name: Assert cluster {{ postgresql_version }}/{{ postgresql_cluster_name }} exists at the default path
ansible.builtin.assert:
that:
- postgresql_reg_pg_version.stat.exists
fail_msg: "No initialised cluster at {{ postgresql_data_dir }}"
quiet: true
- name: List PostgreSQL clusters
ansible.builtin.command:
argv: [pg_lsclusters, --no-header]
register: postgresql_reg_clusters
changed_when: false
check_mode: false
- name: Assert {{ postgresql_version }}/{{ postgresql_cluster_name }} is the only cluster
ansible.builtin.assert:
that:
- postgresql_reg_clusters.stdout_lines | length == 1
- (postgresql_reg_clusters.stdout_lines[0].split())[0] == postgresql_version
- (postgresql_reg_clusters.stdout_lines[0].split())[1] == postgresql_cluster_name
fail_msg: "Unexpected clusters present: {{ postgresql_reg_clusters.stdout_lines }}"
quiet: true
- name: Check that contrib extensions ship with postgresql-{{ postgresql_version }}
ansible.builtin.stat:
path: "/usr/share/postgresql/{{ postgresql_version }}/extension/pg_stat_statements.control"
register: postgresql_reg_contrib
- name: Assert contrib extensions are available
ansible.builtin.assert:
that:
- postgresql_reg_contrib.stat.exists
quiet: true
- name: Ensure the postgresql service is enabled and started
ansible.builtin.systemd_service:
name: "{{ postgresql_service_name }}"
enabled: true
state: started
- name: Ensure the {{ postgresql_cluster_unit }} instance is running
ansible.builtin.systemd_service:
name: "{{ postgresql_cluster_unit }}"
state: started
- name: Ensure cron is enabled and started
ansible.builtin.systemd_service:
name: cron
enabled: true
state: started
roles/postgresql/tasks/configure.yml
Both files are validated before the restart handler fires. postgres -C parses postgresql.conf without starting a second server. pg_hba_file_rules re-reads pg_hba.conf from disk and reports any errors. A typo therefore fails the play while the old config is still live.
---
- name: Set required parameters in postgresql.conf
ansible.builtin.lineinfile:
path: "{{ postgresql_config_dir }}/postgresql.conf"
regexp: '^\s*#?\s*{{ item.key }}\s*='
line: "{{ item.key }} = {{ item.value }}\t\t# managed by Ansible"
owner: postgres
group: postgres
mode: "0644"
backup: true
loop: "{{ postgresql_conf_settings | combine(postgresql_conf_extra_settings) | dict2items }}"
loop_control:
label: "{{ item.key }}"
notify: restart postgresql
- name: Deploy pg_hba.conf
ansible.builtin.template:
src: pg_hba.conf.j2
dest: "{{ postgresql_config_dir }}/pg_hba.conf"
owner: postgres
group: postgres
mode: "0640"
backup: true
notify: restart postgresql
- name: Validate configuration files before any restart
become: true
become_user: postgres
block:
- name: Parse postgresql.conf with the server binary
ansible.builtin.command:
argv:
- "{{ postgresql_bin_dir }}/postgres"
- -c
- "config_file={{ postgresql_config_dir }}/postgresql.conf"
- -C
- shared_buffers
changed_when: false
check_mode: false
- name: Check pg_hba.conf for parse errors
community.postgresql.postgresql_query:
login_db: postgres
query: SELECT line_number, error FROM pg_hba_file_rules WHERE error IS NOT NULL
register: postgresql_reg_hba_errors
changed_when: false
check_mode: false
- name: Fail if pg_hba.conf contains errors
ansible.builtin.fail:
msg: "pg_hba.conf errors (server NOT restarted): {{ postgresql_reg_hba_errors.query_result }}"
when: postgresql_reg_hba_errors.query_result | length > 0
roles/postgresql/templates/pg_hba.conf.j2
Rules are matched top-down. The explicit reject lines provide defense in depth behind UFW.
# {{ ansible_managed }}
# TYPE DATABASE USER ADDRESS METHOD
# Local Unix socket: OS-user identity (required for postgres-run backups/admin)
local all postgres peer
local all all peer
# Loopback TCP
host all all 127.0.0.1/32 {{ postgresql_hba_auth_method }}
host all all ::1/128 {{ postgresql_hba_auth_method }}
# Application subnet
{% for rule in postgresql_hba_app_rules %}
host {{ rule.database }} {{ rule.user }} {{ rule.address }} {{ rule.method | default(postgresql_hba_auth_method) }}
{% endfor %}
# Everything else is rejected
host all all 0.0.0.0/0 reject
host all all ::/0 reject
roles/postgresql/tasks/database.yml
---
- name: Manage the billing database, role and privileges
become: true
become_user: postgres
block:
- name: Create login role {{ postgresql_app_db_user }} without elevated attributes
community.postgresql.postgresql_user:
name: "{{ postgresql_app_db_user }}"
password: "{{ postgresql_app_db_password }}"
role_attr_flags: LOGIN,NOSUPERUSER,NOCREATEDB,NOCREATEROLE,NOREPLICATION,NOBYPASSRLS
state: present
no_log: true
- name: Create database {{ postgresql_app_db_name }}
community.postgresql.postgresql_db:
name: "{{ postgresql_app_db_name }}"
owner: postgres
encoding: "{{ postgresql_app_db_encoding }}"
lc_collate: "{{ postgresql_app_db_locale }}"
lc_ctype: "{{ postgresql_app_db_locale }}"
template: template0
state: present
- name: Grant ALL on database {{ postgresql_app_db_name }} to {{ postgresql_app_db_user }}
community.postgresql.postgresql_privs:
login_db: "{{ postgresql_app_db_name }}"
type: database
objs: "{{ postgresql_app_db_name }}"
privs: ALL
roles: "{{ postgresql_app_db_user }}"
state: present
- name: Grant ALL on schema public in {{ postgresql_app_db_name }} (PG15+ requirement for DDL)
community.postgresql.postgresql_privs:
login_db: "{{ postgresql_app_db_name }}"
type: schema
objs: public
privs: ALL
roles: "{{ postgresql_app_db_user }}"
state: present
when: postgresql_app_grant_public_schema | bool
- name: Revoke default CONNECT/TEMPORARY on {{ postgresql_app_db_name }} from PUBLIC
community.postgresql.postgresql_privs:
login_db: "{{ postgresql_app_db_name }}"
type: database
objs: "{{ postgresql_app_db_name }}"
privs: CONNECT,TEMPORARY
roles: PUBLIC
state: absent
when: postgresql_app_revoke_public_connect | bool
roles/postgresql/tasks/firewall.yml
The allow rules are created before UFW is enabled, so the SSH session cannot be cut off.
---
- name: Allow SSH from anywhere (management access)
community.general.ufw:
rule: "{{ postgresql_ufw_ssh_rule }}"
port: "{{ postgresql_ufw_ssh_port | string }}"
proto: tcp
comment: SSH management access
- name: Allow PostgreSQL only from the application subnet
community.general.ufw:
rule: allow
port: "{{ postgresql_port | string }}"
proto: tcp
src: "{{ postgresql_app_subnet }}"
comment: PostgreSQL from billing app subnet
- name: Set UFW default policy deny for incoming traffic
community.general.ufw:
default: deny
direction: incoming
- name: Set UFW default policy allow for outgoing traffic
community.general.ufw:
default: allow
direction: outgoing
- name: Set UFW default policy deny for routed traffic
community.general.ufw:
default: deny
direction: routed
- name: Set UFW logging level
community.general.ufw:
logging: "{{ postgresql_ufw_logging }}"
- name: Enable UFW
community.general.ufw:
state: enabled
roles/postgresql/tasks/backup.yml
---
- name: Create the backup directory
ansible.builtin.file:
path: "{{ postgresql_backup_dir }}"
state: directory
owner: postgres
group: postgres
mode: "0750"
- name: Install the backup script (root-owned, executable by postgres)
ansible.builtin.template:
src: pg_backup.sh.j2
dest: "{{ postgresql_backup_script }}"
owner: root
group: postgres
mode: "0750"
validate: /bin/bash -n %s
- name: Schedule the nightly backup at {{ postgresql_backup_cron_hour }}:{{ postgresql_backup_cron_minute }} as postgres
ansible.builtin.cron:
name: "pg_dump {{ postgresql_app_db_name }} nightly"
user: postgres
minute: "{{ postgresql_backup_cron_minute }}"
hour: "{{ postgresql_backup_cron_hour }}"
job: "{{ postgresql_backup_script }} 2>&1 | /usr/bin/logger -t pg_backup_{{ postgresql_app_db_name }}"
state: present
roles/postgresql/templates/pg_backup.sh.j2
The script writes each dump to a temporary file, tests it with gzip -t, and then moves it into place atomically. Pruning happens only after a successful dump, so a broken night never deletes good backups.
#!/usr/bin/env bash
# {{ ansible_managed }}
set -Eeuo pipefail
umask 077
DB="{{ postgresql_app_db_name }}"
DIR="{{ postgresql_backup_dir }}"
RETENTION_DAYS="{{ postgresql_backup_retention_days }}"
PG_DUMP="{{ postgresql_bin_dir }}/pg_dump"
STAMP="$(date +%Y%m%d)"
TARGET="${DIR}/${DB}_${STAMP}.sql.gz"
log() { /usr/bin/logger -t "pg_backup_${DB}" -- "$*"; }
trap 'log "FAILED (line ${LINENO}); existing backups left untouched"' ERR
TMP="$(mktemp "${DIR}/.${DB}_${STAMP}.XXXXXX")"
trap 'rm -f "${TMP}"' EXIT
log "starting dump of ${DB}"
"${PG_DUMP}" --no-password --dbname="${DB}" | /usr/bin/gzip -6 > "${TMP}"
/usr/bin/gzip -t "${TMP}"
mv -f "${TMP}" "${TARGET}"
trap - EXIT
log "dump complete: ${TARGET} ($(stat -c %s "${TARGET}") bytes)"
/usr/bin/find "${DIR}" -maxdepth 1 -type f -name "${DB}_*.sql.gz" \
-mmin "+$(( RETENTION_DAYS * 24 * 60 ))" -print -delete \
| while read -r f; do log "pruned ${f}"; done
roles/postgresql/tasks/verify.yml
---
- name: Verify server settings as postgres
become: true
become_user: postgres
block:
- name: Read effective server settings
community.postgresql.postgresql_query:
login_db: postgres
query: >-
SELECT current_setting('data_directory') AS data_directory,
current_setting('listen_addresses') AS listen_addresses,
current_setting('port') AS port,
current_setting('max_connections') AS max_connections,
current_setting('shared_buffers') AS shared_buffers
register: postgresql_reg_settings
changed_when: false
check_mode: false
- name: Assert effective settings match the desired state
ansible.builtin.assert:
that:
- postgresql_reg_settings.query_result[0].data_directory == postgresql_data_dir
- postgresql_reg_settings.query_result[0].listen_addresses == postgresql_listen_addresses
- postgresql_reg_settings.query_result[0].port | int == postgresql_port | int
- postgresql_reg_settings.query_result[0].max_connections | int == postgresql_max_connections | int
- postgresql_reg_settings.query_result[0].shared_buffers == postgresql_shared_buffers
fail_msg: "Settings drift: {{ postgresql_reg_settings.query_result[0] }}"
quiet: true
- name: Read attributes of role {{ postgresql_app_db_user }}
community.postgresql.postgresql_query:
login_db: postgres
query: >-
SELECT rolsuper, rolcreatedb, rolcreaterole, rolreplication, rolcanlogin
FROM pg_roles WHERE rolname = %(role)s
named_args:
role: "{{ postgresql_app_db_user }}"
register: postgresql_reg_role
changed_when: false
check_mode: false
- name: Assert {{ postgresql_app_db_user }} can log in but has no elevated rights
ansible.builtin.assert:
that:
- postgresql_reg_role.query_result | length == 1
- postgresql_reg_role.query_result[0].rolcanlogin
- not postgresql_reg_role.query_result[0].rolsuper
- not postgresql_reg_role.query_result[0].rolcreatedb
- not postgresql_reg_role.query_result[0].rolcreaterole
- not postgresql_reg_role.query_result[0].rolreplication
quiet: true
- name: Check the listening socket
ansible.builtin.command:
argv: [ss, -H, -l, -t, -n, "sport = :{{ postgresql_port }}"]
register: postgresql_reg_ss
changed_when: false
check_mode: false
- name: Assert PostgreSQL listens on 0.0.0.0:{{ postgresql_port }}
ansible.builtin.assert:
that:
- ("0.0.0.0:" ~ postgresql_port) in postgresql_reg_ss.stdout
quiet: true
- name: Test password login over TCP as {{ postgresql_app_db_user }}
community.postgresql.postgresql_ping:
login_host: 127.0.0.1
login_port: "{{ postgresql_port }}"
login_user: "{{ postgresql_app_db_user }}"
login_password: "{{ postgresql_app_db_password }}"
login_db: "{{ postgresql_app_db_name }}"
register: postgresql_reg_ping
no_log: true
- name: Assert {{ postgresql_app_db_user }} authenticated successfully
ansible.builtin.assert:
that:
- postgresql_reg_ping.is_available
fail_msg: "{{ postgresql_app_db_user }} could not authenticate to {{ postgresql_app_db_name }} over TCP"
quiet: true
4. Inventory and variables
inventory.ini
Replace the address with your host. 192.0.2.10 is a documentation placeholder.
[db_servers]
billing-db01 ansible_host=192.0.2.10
[db_servers:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3
group_vars/db_servers/vars.yml
---
postgresql_app_db_name: billing_app
postgresql_app_db_user: billing_svc
postgresql_app_db_password: "{{ vault_billing_svc_password }}"
postgresql_app_subnet: 10.20.30.0/24
postgresql_listen_addresses: "0.0.0.0"
postgresql_port: 5432
postgresql_max_connections: 100
postgresql_shared_buffers: "256MB"
postgresql_backup_retention_days: 14
group_vars/db_servers/vault.yml
Create the file with ansible-vault create. It should only ever be stored encrypted. The plaintext content you type into the editor is:
---
vault_billing_svc_password: "REPLACE_WITH_GENERATED_SECRET"
On disk it then looks like this:
$ANSIBLE_VAULT;1.1;AES256
6231386466...(encrypted payload)...
5. Run instructions
cd postgres-billing
# 1. Collections
ansible-galaxy collection install -r requirements.yml
# 2. Secret (generate, then paste into the vault editor)
openssl rand -base64 33 | tr -d '/+=\n'; echo
ansible-vault create group_vars/db_servers/vault.yml --vault-password-file ~/.vault_pass.txt
# 3. Connectivity and syntax
ansible db_servers -m ansible.builtin.ping
ansible-playbook site.yml --syntax-check
# 4. Dry run with diff
# On the brand-new VM, stages that need installed packages are skipped (a warning is printed).
# On later runs, check mode covers everything.
ansible-playbook site.yml --check --diff --vault-password-file ~/.vault_pass.txt
# 5. Apply
ansible-playbook site.yml --diff --vault-password-file ~/.vault_pass.txt
# Selective runs
ansible-playbook site.yml --diff --tags config # postgresql.conf / pg_hba.conf only
ansible-playbook site.yml --diff --tags firewall
ansible-playbook site.yml --diff --tags backup
ansible-playbook site.yml --tags verify # read-only health check
6. Rollback and recovery notes
- Bad config: both files are validated before the restart, so a parse error fails the play with the old config still running. If the restart itself fails (for example, the kernel rejects the shared memory size), the timestamped backups are kept next to the originals:
ls -l /etc/postgresql/16/main/*.conf.*~ sudo cp -p /etc/postgresql/16/main/pg_hba.conf.<timestamp>~ /etc/postgresql/16/main/pg_hba.conf sudo systemctl restart postgresql@16-main sudo journalctl -u postgresql@16-main -n 50; sudo tail -n 50 /var/log/postgresql/postgresql-16-main.log - Firewall: the preflight port assert and the rule ordering prevent lockout. If you are locked out anyway, use the hypervisor console and run
sudo ufw disable, then re-run with--tags firewall. - Packages: this is a fresh host, so a full rollback is
apt purge postgresql-16 postgresql-client-16plus removing/etc/apt/sources.list.d/pgdg.listand/etc/apt/preferences.d/pgdg.pref. The purge destroys the data directory. - Password rotation: run
ansible-vault edit group_vars/db_servers/vault.yml, then--tags database. - Restore a dump into an empty
billing_app:gunzip -c /var/backups/postgresql/billing_app_YYYYMMDD.sql.gz | sudo -u postgres psql -v ON_ERROR_STOP=1 -d billing_app - Backups live on the same disk as the data. Ship them off-host (object storage or a backup server) for real disaster recovery.
Validation
Static checks
ansible-playbook site.yml --syntax-check
ansible-lint site.yml roles/postgresql
Idempotency: run the apply command a second time. The recap should show changed=0.
On the target host
apt-cache policy postgresql-16 # candidate from apt.postgresql.org, priority 900
pg_lsclusters # exactly one line: 16 main 5432 online ... /var/lib/postgresql/16/main
systemctl is-enabled postgresql; systemctl is-active postgresql@16-main
ss -ltn 'sport = :5432' # 0.0.0.0:5432
sudo -u postgres psql -Atc "SHOW max_connections; SHOW shared_buffers; SHOW listen_addresses;"
sudo -u postgres psql -Atc "SELECT rolsuper, rolcreatedb, rolcreaterole FROM pg_roles WHERE rolname='billing_svc';" # f|f|f
sudo -u postgres psql -d billing_app -c '\l billing_app' # ACL shows billing_svc=CTc, no "=Tc" for PUBLIC
sudo ufw status verbose # deny (incoming), 22/tcp ALLOW Anywhere, 5432/tcp ALLOW 10.20.30.0/24
sudo -u postgres crontab -l # 30 2 * * * /usr/local/bin/pg_backup_billing_app.sh ...
sudo -u postgres /usr/local/bin/pg_backup_billing_app.sh && ls -l /var/backups/postgresql/
gzip -t /var/backups/postgresql/billing_app_$(date +%Y%m%d).sql.gz && echo OK
journalctl -t pg_backup_billing_app -n 20
Network tests
- From a host in
10.20.30.0/24:psql "host=<db-ip> dbname=billing_app user=billing_svc" -c 'select 1'succeeds. - From the same host,
dbname=postgresis rejected bypg_hba. - From a host outside the subnet:
nc -zv <db-ip> 5432times out because UFW drops the packets. - SSH on port 22 still works from anywhere.
Related prompts
Kubernetes Resource Diagnostics
Diagnoses a failing Kubernetes resource and returns root cause plus a step-by-step fix.
Cybersecurity Audit Specialist
Run a structured cybersecurity audit of an organization, prioritizing risks and producing an actionable remediation roadmap.
DevOps Automation Specialist
Acts as a DevOps engineer to design, optimize, and troubleshoot CI/CD pipelines, infrastructure as code, and cloud automation.
Cloud Infrastructure Architect
Design a scalable, secure, cost-optimized cloud architecture with IaC, diagrams, and a phased rollout plan.