brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: a ~/.pgpass file lets psql and pg_dump log in to PostgreSQL without a prompt

Postgresql
~/tips/tip-postgresql-pgpass-file

echo 'db1.example.com:5432:*:backup:change-me' >> ~/.pgpass

Stores PostgreSQL passwords per host and user in a private file that all client tools read.

A backup script that calls pg_dump stops and waits when it asks for a password. Putting the password in PGPASSWORD works, but environment variables leak into process listings on some systems. libpq has a file for this.

echo 'db1.example.com:5432:*:backup:change-me' >> ~/.pgpass
chmod 600 ~/.pgpass
pg_dump -h db1.example.com -U backup -Fc -f appdb.dump appdb

Each line has five fields: host, port, database, user and password. The first four can be * for anything. psql, pg_dump, pg_restore and every other tool built on libpq read the file and use the password from the first line that matches the connection. So put the specific lines first and the ones with wildcards last.

The database field rarely matters, since a user has the same password in every database of a server. I’d keep it at *.

The chmod 600 is required. The docs say a file that group or others can read is ignored, and then you get a password prompt with no clear reason. For a local socket connection, the host field must be localhost. Want a separate file per job? Point PGPASSFILE at it. And a colon or backslash inside a password must be escaped with a backslash, which is easy to forget with generated passwords.

Further reading: The password file

More Postgresql tips FROM pg_settings FROM pg_hba_file_rules LOAD 'auto_explain'; CREATE EXTENSION pgstattuple; pg_dump -O -x -f mydb.sql mydb All Postgresql tips (24) All topics

Link