Skip to content

Create Postgres Backup #1

Create Postgres Backup

Create Postgres Backup #1

name: Create Postgres Backup
on:
workflow_dispatch:
# on:
# schedule:
# - cron: '0 0 * * *' # Runs at 00:00 UTC daily.
jobs:
backup_upload:
runs-on: ubuntu-latest
environment: prod
steps:
- name: Setup SSH
run: |
mkdir -p ~/.ssh
echo "${{ secrets.SSH_PRIVATE_KEY }}" > ~/.ssh/private_key.pem
chmod 600 ~/.ssh/private_key.pem
ssh-keyscan -H ${{ secrets.SERVER_HOST }} >> ~/.ssh/known_hosts
- name: Create and Upload Backup
run: |
BACKUP_NAME="pg_backup_$(date +%Y-%m-%dT%H-%M-%S).sql.gz"
echo "Backup name is : $BACKUP_NAME"
ssh -i ~/.ssh/private_key.pem ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }} <<ENDSSH
echo "Checking Docker status:"
docker info
echo "Listing containers:"
docker ps --all
CONTAINER_NAME=\$(docker ps --format '{{.Names}}' | grep db)
echo "Container name is: \$CONTAINER_NAME"
echo "Creating database backup..."
docker exec \$CONTAINER_NAME pg_dump -U postgres -h localhost trackdb | gzip > /tmp/$BACKUP_NAME
echo "Done creating database backup."
ENDSSH
scp -i ~/.ssh/private_key.pem ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }}:/tmp/$BACKUP_NAME .
ssh -i ~/.ssh/private_key.pem ${{ secrets.SERVER_USER }}@${{ secrets.SERVER_HOST }} "rm /tmp/$BACKUP_NAME"
echo '${{ secrets.GCP_SA_KEY }}' > /tmp/gcp-sa-key.json
gcloud auth activate-service-account --key-file=/tmp/gcp-sa-key.json
gsutil cp ./$BACKUP_NAME gs://ocho-osai/track/pg_data/$BACKUP_NAME
rm /tmp/gcp-sa-key.json $BACKUP_NAME