Sub topic 5
Backing up roles and other cluster-wide objects
This chapter assumes you can use psql and the Linux shell, and that you know PostgreSQL has roles, databases, and a data directory. You should also have read the previous chapters on pg_dump and dump formats.
A pg_dump file describes one database. A PostgreSQL server (a cluster) also holds objects that belong to no single database. If you restore a dump on a fresh server without them, the restore fails or produces objects with the wrong owners. This chapter covers what those objects are, how to save them with pg_dumpall, and the order in which to restore everything.
What lives outside a single database
Some catalog data is shared across the whole cluster. The following objects are not part of any database dump:
- Roles. Users and groups, including login rights, attributes such as
SUPERUSERorCREATEDB, and password hashes. - Role memberships. Which role is a member of which group role.
- Tablespace definitions. The name of each tablespace and the directory it points to.
- Role and database settings.
ALTER ROLE ... SETvalues, such as a defaultsearch_pathfor one user.
A pg_dump file does contain statements that refer to roles. Tables have OWNER TO clauses, and permissions appear as GRANT statements. It never contains the CREATE ROLE statements those references need.
| Item | In `pg_dump` of one database | In `pg_dumpall --globals-only` |
|---|---|---|
| Table data and schema | Yes | No |
| `CREATE ROLE` and attributes | No | Yes |
| Role memberships | No | Yes |
| `CREATE TABLESPACE` | No | Yes |
| `OWNER TO` and `GRANT` lines | Yes (they refer to roles) | No |
| `postgresql.conf`, `pg_hba.conf` | No | No |
The last row matters. Configuration files are not part of any SQL dump, so you must copy them with your normal file backups.
Dumping globals with pg_dumpall
pg_dumpall is a client program like pg_dump. It connects to the server and writes plain SQL to standard output. Without options it dumps every database plus the globals. For a backup strategy that uses custom or directory format for the databases, you usually want only the globals:
pg_dumpall -U postgres --globals-only > globals.sql
psql -U postgres -d postgres -f globals.sqlThe first command writes the file on the source server. The second replays it on the target cluster. Run the second command on the target, after copying the file there.
Two narrower options exist:
--roles-onlydumps roles and memberships, without tablespaces.--tablespaces-onlydumps only the tablespace definitions.
Use them when you want to restore one part without the other. For example, a target server may lay out its disks differently, so you want the roles but not the tablespaces.
What the output looks like
Open the file and read it. The structure is easy to follow:
grep -E '^(CREATE|ALTER) ROLE|^CREATE TABLESPACE|^GRANT' globals.sql | head -n 20You will see lines such as CREATE ROLE app_user; followed by ALTER ROLE app_user WITH NOSUPERUSER INHERIT LOGIN ... PASSWORD 'SCRAM-SHA-256$...'. Memberships appear as GRANT statements. Tablespaces appear as CREATE TABLESPACE name OWNER role LOCATION '/path';.
Password hashes are in the file
The dump contains each role's stored password hash. It is a hash, not plain text, but anyone who can read the file can try to crack it offline. Treat globals.sql like a credential:
( umask 077; pg_dumpall -U postgres --globals-only > globals.sql )
ls -l globals.sqlThe umask 077 makes the file readable only by its owner. Encrypt it before it leaves the server (see the chapter on retention and offsite copies).
Reading hashes requires superuser access, because they live in pg_authid. If you cannot or do not want to carry hashes, add --no-role-passwords. The roles are recreated without passwords, and you set them afterwards. This option also lets a non-superuser run the dump, since it reads the pg_roles view instead.
pg_dumpall -U postgres --globals-only --no-role-passwords > globals_nopw.sqlRestore order and expected errors
Restore the globals first. A database restore that runs before its roles exist produces errors such as role "app_user" does not exist on every ALTER ... OWNER TO and GRANT. The usual order is:
- Restore
globals.sqlinto thepostgresdatabase on the target cluster. - Create each target database and restore its dump with
pg_restoreorpsql. - Check ownership and permissions.
Here is a typical session on a new server:
psql -U postgres -d postgres -f globals.sql
createdb -U postgres mydb_restored
pg_restore -U postgres -d mydb_restored mydb.dumpThe "role already exists" message
The dump includes CREATE ROLE postgres;, and the bootstrap superuser already exists on any new cluster. You will see this error when replaying the file:
ERROR: role "postgres" already existsThis is expected. The ALTER ROLE postgres ... that follows still applies, so the superuser's attributes and password are set to the source values. Do not run the replay with ON_ERROR_STOP=1, or it will stop at this first line. If you want a clean log, remove the CREATE ROLE postgres; line from the file before replaying.
If your cluster's bootstrap superuser has a different name, the same message appears for that name.
Tablespaces need directories first
A CREATE TABLESPACE statement points at a directory. PostgreSQL does not create the directory. It must already exist, be empty, and be owned by the operating system user that runs the server. If it is missing, the statement fails with an error like directory "/data/ts1" does not exist.
The consequence is that restoring globals onto a server with a different disk layout needs one of two approaches:
- Create the same directories on the target before replaying
globals.sql. - Edit the
LOCATIONpaths in the file, or use--roles-onlyand create the tablespaces yourself.
If a table in a dump is assigned to a tablespace that does not exist on the target, that table's CREATE fails. You can avoid the problem entirely by dumping with pg_dump --no-tablespaces, which leaves every object in the default tablespace on restore. Only the tablespace definition is in globals.sql. The data inside the tablespace comes from the database dumps.
Settings that belong to roles and databases
ALTER ROLE app_user SET search_path = app, public; is a cluster-level fact. ALTER ROLE app_user IN DATABASE mydb SET work_mem = '64MB'; is as well. pg_dumpall writes both into the globals output, so replay brings them back. Per-database settings (ALTER DATABASE ... SET) are included by pg_dump --create, and pg_dumpall also includes them when it dumps whole databases.
A common surprise is a restored application that behaves differently, for example by picking the wrong schema. Look for missing role settings before you blame the data.
Choosing the options
You have three ways to get roles into a new cluster. This table shows when each fits:
| Approach | Use when | Watch for |
|---|---|---|
| `pg_dumpall --globals-only` | Rebuilding a whole server from per-database dumps | Hash exposure, the `postgres` error, tablespace paths |
| `pg_dumpall --roles-only` | The target has its own disk layout | You create tablespaces yourself |
| `pg_dump --no-owner --no-privileges` | Copying one database to a server with different roles | Objects belong to the restoring user and permissions are lost |
The last row skips globals entirely. With --no-owner, every restored object is owned by the user who runs the restore. With --no-privileges, no GRANT statements run. This approach suits a development copy of a production database. It does not suit a disaster recovery, where permissions must come back exactly as they were.
Automating the globals dump
Dump the globals every time you dump databases, and keep them together. Roles change less often than data, but they change, and a stale globals file silently breaks a restore months later. This script writes both into one dated directory:
#!/usr/bin/env bash
set -euo pipefail
stamp=$(date +%Y%m%d_%H%M%S)
dest="/backups/$stamp"
mkdir -p "$dest"
chmod 700 "$dest"
pg_dumpall -U postgres --globals-only > "$dest/globals.sql"
pg_dump -U postgres -Fc -f "$dest/mydb.dump" mydbFor a cluster with many databases, loop over psql -Atc "SELECT datname FROM pg_database WHERE NOT datistemplate AND datallowconn" and dump each one. The script needs a .pgpass entry or another non-interactive way to authenticate, because pg_dumpall may open several connections and prompt for a password each time.
Common errors
role "x" does not existduringpg_restore. The globals were not replayed first. Replay them, then restore the database again into a fresh empty database.permission denied for table pg_authid. The dump user is not a superuser. Use a superuser, or add--no-role-passwords.directory "..." does not existonCREATE TABLESPACE. Create the directory, with the right owner, before replaying.- Roles restored without passwords. The dump used
--no-role-passwords. Set passwords withALTER ROLE ... PASSWORD.
Exercise
You restore a custom-format dump of salesdb onto a new server and see hundreds of role "report_user" does not exist errors on GRANT and ALTER ... OWNER TO statements. What went wrong, and how do you fix it?
Show answer
The cluster-wide roles were never created on the new server, because pg_dump does not include roles. Take pg_dumpall --globals-only on the source (or use the existing file), replay it on the target with psql -d postgres -f globals.sql, and then drop and recreate the target database and run pg_restore again. The role "postgres" already exists message during the replay is expected.
Exercise
Your security team says backups must not contain anything that lets an attacker try to crack user passwords offline. Which option do you add to the globals dump, and what must you do after restoring?
Show answer
Add --no-role-passwords to pg_dumpall --globals-only. The file then has no password hashes. After restoring, set a password for each login role with ALTER ROLE name PASSWORD '...', or switch those roles to another authentication method.