← Catalog Matrix

Deployment Execution Blueprint

---
title: Automated PostgreSQL Backup to AWS S3 Script
description: A zero-dependency Bash script to automate PostgreSQL database dumps, compress files, upload safely to AWS S3, and auto-clean old backups.
category: DevOps
slug: bash-automated-postgresql-s3-backup
keywords: postgresql s3 backup script, automate postgres dump s3, bash script backup database aws, pg_dump s3 lifecycle
---

### Overview & Problem Matrix
Losing a production database instance due to unexpected hardware failure, filesystem corruption, or bad deployments is a catastrophic server emergency. 

Manually triggering relational database extractions is highly inconsistent, while installing heavy third-party backup agents introduces complex application security dependencies. You need a streamlined, zero-dependency cron utility that safely packages your dataset, ships it to secure offsite object storage, and manages storage overhead automatically.

### Implementation Guide & Setup Steps
To implement this secure, automated cloud database backup pipeline within your environment, execute these administration steps:

1. Map Database Credentials Securely: To prevent the script from hanging on password prompts or exposing keys in plain text, map your credentials to a protected file located at `~/.pgpass` or inside your active environment mapping variables:
   $ echo "localhost:5432:your_db_name:your_user:your_password" > ~/.pgpass
   $ chmod 600 ~/.pgpass

2. Connect Your AWS Core CLI: Ensure your server has the official AWS Command Line Interface binaries installed. Authenticate your instance profiles using an IAM user with explicit write permissions to your target storage container:
   $ aws configure

3. Automate the Script Routine: Save the automation script layout below as `postgres_s3_backup.sh`. Elevate its execution privileges and assign it to your system crontab cluster to execute quietly every single morning at 2:00 AM:
   $ chmod 700 /usr/local/bin/postgres_s3_backup.sh
   $ crontab -e
   
   # Add this execution sequence to the crontab config file:
   0 2 * * * /bin/bash /usr/local/bin/postgres_s3_backup.sh > /dev/null 2>&1

#!/bin/bash

# Configuration: Define your tracking variables and storage paths safely
DB_NAME="your_database_name"
DB_USER="your_database_user"
S3_BUCKET="s3://your-bucket-name/backups/postgres"
LOCAL_BACKUP_DIR="/var/backups/postgres"
RETENTION_DAYS=7

# Establish unique chronological timestamp indexes
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
BACKUP_FILE="${LOCAL_BACKUP_DIR}/${DB_NAME}_backup_${TIMESTAMP}.sql.gz"
LOG_FILE="/var/log/postgres_backup.log"

# Validate that local system directory architectures exist safely
mkdir -p "$LOCAL_BACKUP_DIR"

echo "[$(date)] Launching automated database extraction matrix for: ${DB_NAME}" >> "$LOG_FILE"

# 1. Execute database dump routing strings directly into localized gzip compression
if pg_dump -U "$DB_USER" "$DB_NAME" | gzip > "$BACKUP_FILE"; then
    echo "[$(date)] Success: Local relational backup written to disk at ${BACKUP_FILE}" >> "$LOG_FILE"
else
    echo "[$(date)] CRITICAL ERROR: PostgreSQL dump sequence dropped execution pipelines." >> "$LOG_FILE"
    exit 1
fi

# 2. Upload the compressed archive bundle to your private remote AWS S3 object store
if aws s3 cp "$BACKUP_FILE" "${S3_BUCKET}/${DB_NAME}_backup_${TIMESTAMP}.sql.gz"; then
    echo "[$(date)] Success: Archive transmitted to remote S3 bucket node storage." >> "$LOG_FILE"
else
    echo "[$(date)] CRITICAL ERROR: AWS S3 connection or upload configuration dropped." >> "$LOG_FILE"
    exit 1
fi

# 3. Apply local retention housecleaning rules to purge historical assets
echo "[$(date)] Executing localized lifecycle maintenance cleanup..." >> "$LOG_FILE"
find "$LOCAL_BACKUP_DIR" -type f -name "${DB_NAME}_backup_*.sql.gz" -mtime +$RETENTION_DAYS -exec rm -f {} \;

echo "[$(date)] Infrastructure backup routine completed successfully." >> "$LOG_FILE"