How to Anonymize a pg_dump: Share PostgreSQL Dumps Without Personal Data

Sooner or later someone asks for "a copy of the production database" to debug an issue, seed a staging environment or hand to a contractor. The quick answer is pg_dump, but a plain dump contains every email address, phone number, card number and support ticket you hold. This guide shows three practical ways to get an anonymized pg_dump, with the trade-offs of each, and a complete walkthrough of the read-only approach.

Why you should not share a raw pg_dump

A pg_dump file is a full copy of your data in plain text (or a custom archive that restores to plain text). Once it is on a laptop, in a Slack upload or in a CI artifact, you have lost control of it. Under GDPR and similar laws, a staging database filled with real customer data is still personal data with all the same obligations. Masking the data before it leaves production is the simplest way to stay out of trouble. See GDPR and test data for the compliance side.

You have three options.

Option 1: restore, scrub with SQL, then dump again

The do-it-yourself route: restore the real dump into a throwaway database, run UPDATE statements over the sensitive columns, then pg_dump the scrubbed copy.

createdb scratch
pg_restore -d scratch prod.dump
psql scratch -c "UPDATE users SET email = 'user' || id || '@example.com', full_name = 'User ' || id, phone = NULL;"
pg_dump -Fc scratch > scrubbed.dump
dropdb scratch

It works and needs no extra tools, but it has real downsides:

  • The unmasked data still travels to wherever the scratch database lives.
  • Fake values like User 42 are unrealistic, so UI and search bugs hide.
  • You have to keep the SQL in sync with every migration, and it is easy to miss a column (a JSONB field, a free-text notes column).
  • Large tables mean long-running updates and table bloat.

Option 2: anonymous dumps with the PostgreSQL Anonymizer extension

If you control the PostgreSQL server, the PostgreSQL Anonymizer extension lets you declare masking rules inside the database and export anonymous dumps. It is a strong choice when you can install extensions and want rules stored with the schema. It requires loading anon through shared_preload_libraries, which some managed providers do not allow. We compare it with other tools in PostgreSQL data masking tools compared.

Option 3: produce the anonymized dump directly, read-only

Cloud-DB-Anonymizer is a free, MIT-licensed Python CLI that replaces the "dump, then scrub" dance with one step. It connects to the live database with a read-only user, uses pg_dump only for the schema, streams the rows through masking strategies and writes a gzip SQL file you restore with psql. Nothing is written to the source database, and real values never land on disk.

One thing to be clear about: it reads from a database, not from an existing dump file. If all you have is a .dump file, restore it into a private database first and point the CLI at that.

Step 1: install

git clone https://github.com/fadadyounes-pixel/cloud-db-anonymizer.git
cd cloud-db-anonymizer
python -m venv .venv && source .venv/bin/activate
pip install -r requirements.txt

You need Python 3.10+, PostgreSQL 12+ and the PostgreSQL client tools so pg_dump is on your PATH. Use a pg_dump whose major version is the same as or newer than your server. Without pg_dump you get a data-only dump.

Step 2: create a secret salt

export ANON_SALT=$(openssl rand -hex 32)

Every fake value is derived from HMAC-SHA256 of the real value and this salt. The same real email always becomes the same fake email, in every table and on every run, so foreign keys, joins and unique indexes keep working. Keep the salt secret and stable; rotate it when you want a completely new data set.

Step 3: describe the PII columns

Run python main.py init for a starter file, then edit it:

{
  "schema": "public",
  "exclude_tables": ["audit_logs", "sessions"],
  "tables": {
    "users":    { "columns": { "email": "email", "full_name": "name", "phone": "phone", "date_of_birth": "date_of_birth" } },
    "payments": { "columns": { "card_number": "credit_card", "iban": "iban" } },
    "support_tickets": {
      "columns": { "body": "redact" },
      "where": "created_at > now() - interval '90 days'"
    },
    "uploads":  { "skip_data": true }
  }
}

Tables you do not list are copied as they are; exclude_tables drops tables entirely, skip_data keeps only the schema, and where limits the rows. There are 20 strategies, including email, name, phone, credit_card (Luhn-valid), iban, ssn, address, ip, hash, redact, null and keep. List them with examples:

python main.py strategies
python main.py preview jane.doe@acme.com --strategy email

Step 4: dry-run against the live schema

python main.py sanitize --db-url "$DATABASE_URL" --rules rules.json --dry-run

The dry run compares your rules with the real schema, prints the plan table and warns about any rule that points at a table or column that does not exist. Read those warnings: a typo or a renamed column is how unmasked data slips through.

Step 5: export the anonymized dump

python main.py sanitize --db-url "$DATABASE_URL" --rules rules.json -o sanitized.sql.gz

The whole export runs in one REPEATABLE READ, READ ONLY transaction, so you get a consistent snapshot even while the application keeps writing. Rows are written in foreign-key order, sequences and identity columns are reset, and JSONB and array columns are handled.

Step 6: restore it anywhere

createdb dev_copy
gunzip -c sanitized.sql.gz | psql "postgresql://localhost/dev_copy"

Optional: upload instead of passing files around

Instead of emailing a file, upload it to one S3-compatible bucket and share access through your cloud provider:

python main.py sanitize --db-url "$DATABASE_URL" --rules rules.json --upload sanitized-dumps
# Cloudflare R2, DigitalOcean Spaces or MinIO
python main.py sync sanitized.sql.gz -b sanitized-dumps --endpoint-url https://<ACCOUNT_ID>.r2.cloudflarestorage.com

Checklist before you share any dump

  • Use a read-only database user for the export.
  • Search the schema for columns named like email, phone, name, address, token, notes and JSONB fields, and cover each one in your rules.
  • Hash or redact secrets such as API keys and password reset tokens.
  • Drop or skip session, log and audit tables.
  • Keep rules.json in version control and review it with every migration.
  • Spot-check the restored copy with a few SELECT queries before handing it over.

Automating it

Once the rules are right, the export is one command, so it is easy to run on a schedule or in CI; see anonymizing PostgreSQL in GitHub Actions. If you would rather have a dashboard, a rules editor, a cron scheduler, parallel uploads to AWS S3, Cloudflare R2 and DigitalOcean Spaces with retention pruning, and Telegram or Discord alerts, the self-hosted Pro Suite runs all of it in your own Docker Compose stack. More details are on the project page.