-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackup-docker-psql
executable file
·123 lines (105 loc) · 2.68 KB
/
backup-docker-psql
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#!/bin/bash
# Script to backup postgresql containers
# When no args are specified, it will try to guess the settings
_RED='\033[0;31m'
_ORANGE='\033[0;33m'
_BOLD_BLUE='\033[1;34m'
_NC='\033[0m'
_show_usage() {
echo "$0 --container [container] --name [db_name] --user [db_user]"
}
_show_error() {
echo -e "${_RED}${1}${_NC}" 1>&2
}
_show_title() {
echo -e "${_BOLD_BLUE}${1}${_NC}" 1>&2
}
_debug() {
# shellcheck disable=SC2154
if [[ "${DEBUG}" -eq 1 ]]; then
echo -e "${_ORANGE}${1}${_NC}" 1>&2
fi
}
_backup() {
if [[ -z "${_DB_NAME}" ]]; then
_debug "No database specified, fetching local config file"
# shellcheck disable=SC1091
if source .env 2>/dev/null; then
# shellcheck disable=SC2154
_debug "from env file: ${POSTGRES_DB}"
# shellcheck disable=SC2154
_debug "from env file: ${POSTGRES_USER}"
fi
if [[ -z "${POSTGRES_DB}" || -z "${POSTGRES_USER}" ]]; then
_show_error "Cannot guess DB name or user"
_show_usage
exit 2
fi
_DB_NAME=${POSTGRES_DB}
_DB_USER=${POSTGRES_USER}
fi
if [[ -z ${_CONTAINER} ]]; then
_debug "No container specified, guessing container name"
if (command -v jq && command -v yq) &>/dev/null; then
_CONTAINER=$(yq ".services[].container_name" <docker-compose.yml | grep "postgres" | tr -d \")
fi
if [[ -z "${_CONTAINER}" ]]; then
_CONTAINER=$(docker ps --format "{{.Names}}" | grep "postgres")
fi
if [[ -z "${_CONTAINER}" ]]; then
_show_error "Cannot find a matching container"
_show_usage
exit 1
fi
if [[ "${_CONTAINER}" == *$'\n'* ]]; then
_show_error "Found multiple Postgres containers:"
_show_error "${_CONTAINER}"
_show_error "Please choose one"
exit 1
fi
fi
_BACKUP_NAME="${_CONTAINER}-$(date +'%Y%m%d').backup"
_show_title "Postgres database backup"
echo -e "Container:\t${_CONTAINER}"
echo -e "Database name:\t${_DB_NAME}"
echo -e "Databaser user:\t${_DB_USER}"
echo -e "Backup name:\t${_BACKUP_NAME}"
if [[ "${_CONFIRM}" != 1 ]]; then
echo -n "Is this ok?? [y/N]: "
read -r continue
if [[ ${continue} != "y" ]]; then
echo "Opertion aborted" && exit 3
fi
fi
echo
docker exec "${_CONTAINER}" pg_dump -U "${_DB_USER}" -Fc "${_DB_NAME}" >"${_BACKUP_NAME}"
}
while [[ $# -gt 0 ]]; do
key="$1"
case ${key} in
-n | --name)
_DB_NAME="$2"
shift
;;
-u | --user)
_DB_USER="$2"
shift
;;
-c | --container)
_CONTAINER="$2"
shift
;;
-y)
_CONFIRM=1
;;
-h | --help | help)
_show_usage && exit 0
;;
*)
# unknown option
_show_usage && exit 0
;;
esac
shift # past argument or value
done
_backup