In Discourse, backups generated while the S3 upload feature is enabled often cannot be used successfully to restore the site, rendering automatic backups effectively invalid. To address this issue, I wrote this script which disables S3 uploads before starting the backup, ensuring that backup files are complete and usable. After the backup finishes, the script re-enables S3 uploads to maintain normal site operations and file storage.
Additionally, the script enables Read-Only Mode during the backup and update process to prevent data writes and ensure consistency. Finally, it automatically pulls the latest code updates and rebuilds the Docker container to complete the maintenance cycle.
I hope this script can help fellow Discourse administrators. Feedback and suggestions for improvement are welcome!
#!/bin/bash
set -e
LOG_FILE="/var/discourse/scripts/weekly_update.log"
log() {
echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG_FILE"
}
log "=== Weekly Discourse Update Started ==="
cd /var/discourse || { log "Failed to cd /var/discourse"; exit 1; }
log "Enabling Read-Only Mode..."
sudo docker exec app rails runner "Discourse.enable_readonly_mode(Discourse::USER_READONLY_MODE_KEY); puts 'Readonly mode enabled'" >> "$LOG_FILE" 2>&1
log "Disabling S3 uploads..."
sudo docker exec app rails runner "SiteSetting.enable_s3_uploads = false" >> "$LOG_FILE" 2>&1
log "Starting backup..."
if ! sudo docker exec app discourse backup >> "$LOG_FILE" 2>&1; then
log "Backup failed"
exit 1
fi
log "Backup succeeded."
log "Enabling S3 uploads..."
sudo docker exec app rails runner "SiteSetting.enable_s3_uploads = true" >> "$LOG_FILE" 2>&1
log "Disabling Read-Only Mode..."
sudo docker exec app rails runner "Discourse.disable_readonly_mode(Discourse::USER_READONLY_MODE_KEY); puts 'Readonly mode disabled'" >> "$LOG_FILE" 2>&1
log "Pulling latest git changes..."
git pull >> "$LOG_FILE" 2>&1
log "Rebuilding container..."
./launcher rebuild app >> "$LOG_FILE" 2>&1
log "Weekly update complete."
exit 0