dotfiles/devops/bin/k8s-pgdb.sh

45 lines
1004 B
Bash
Raw Normal View History

2021-01-15 03:57:38 +00:00
#!/bin/sh
set -e
2021-01-17 16:33:07 +00:00
if [ "$#" -lt 3 ] ;then
echo "Backup/Restore postgres database on k8s"
2021-01-15 03:57:38 +00:00
echo
2021-01-17 16:33:07 +00:00
echo " Usage $0 <backup|restore> <path/to/dbname.sql.gz> <pod-app-label> [container] [dbname]"
2021-01-15 03:57:38 +00:00
exit 1
fi
2021-01-17 16:33:07 +00:00
GZP=$2
2021-01-15 03:57:38 +00:00
APP=$3
2021-01-17 16:33:07 +00:00
CTN=$4
DBN=${5-"$(basename "$GZP" .sql.gz)"}
POD=$(kubectl get pod --selector "app=$APP" | tail +2 | head -n 1 | awk '{print $1}')
2021-01-15 03:57:38 +00:00
if [ -z "$POD" ] ; then
echo not pod found!
exit 1
2021-01-17 16:33:07 +00:00
elif [ "$(echo "$POD" | wc -w)" -gt 1 ] ;then
echo more than one pod!
exit 1
2021-01-15 03:57:38 +00:00
fi
backup () {
2021-01-17 16:33:07 +00:00
kubectl exec "$POD" -c "$CTN" -- sh -c "pg_dump -U postgres --no-owner $DBN | gzip" > "$GZP"
2021-01-15 03:57:38 +00:00
}
restore () {
2021-01-17 16:33:07 +00:00
kubectl exec "$POD" -c "$CTN" -- psql postgres postgres -c "DROP DATABASE IF EXISTS $DBN"
kubectl exec "$POD" -c "$CTN" -- psql postgres postgres -c "CREATE DATABASE $DBN"
kubectl exec "$POD" -c "$CTN" -i -- sh -c "gunzip -c | psql $DBN postgres" < "$GZP"
2021-01-15 03:57:38 +00:00
}
case $1 in
backup)
backup
;;
restore)
restore
;;
esac