Skip to content

Commit 5c1126d

Browse files
authored
Merge pull request #11 from nipreps/codex/create-crontab-script-for-daily-database-backup
Improve MongoDB backup secret handling
2 parents 3de151f + 6bd3ba7 commit 5c1126d

File tree

2 files changed

+34
-5
lines changed

2 files changed

+34
-5
lines changed

README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -51,3 +51,14 @@ Make it executable before scheduling it with `cron`:
5151
```bash
5252
chmod +x scripts/backup_mongodb.sh
5353
```
54+
Store `DBNAME` (and optional credentials) in environment variables rather than
55+
editing the script. You may create a file named `~/.mongodb_backup_env` with
56+
content like:
57+
58+
```bash
59+
export DBNAME="fmriprep_stats"
60+
# export MONGO_USER=myuser
61+
# export MONGO_PASS=mypassword
62+
```
63+
64+
The backup script will source this file if present.

scripts/backup_mongodb.sh

Lines changed: 23 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,20 @@
22
# scripts/backup_mongodb.sh
33
# Backup MongoDB database, ensuring mongod is running.
44

5+
set -euo pipefail
6+
7+
# Optionally source credentials from ~/.mongodb_backup_env
8+
ENV_FILE="$HOME/.mongodb_backup_env"
9+
if [ -f "$ENV_FILE" ]; then
10+
# shellcheck disable=SC1090
11+
source "$ENV_FILE"
12+
fi
13+
14+
# DBNAME is required; credentials are optional
15+
: "${DBNAME:?Set DBNAME, e.g., export DBNAME=your_db}"
16+
517
DATE=$(date +%Y-%m-%d)
6-
BACKUP_DIR="$HOME/Dropbox/backups"
7-
DBNAME="DBNAME"
8-
USERNAME="USERNAME"
9-
PASSWORD="PASSWORD"
18+
BACKUP_DIR="$HOME/Dropbox/fmriprep_stats"
1019
BACKUP_PATH="$BACKUP_DIR/db_backup_${DATE}"
1120

1221
mkdir -p "$BACKUP_DIR"
@@ -27,8 +36,17 @@ else
2736
started_mongod=true
2837
fi
2938

39+
# Build mongodump options
40+
dump_opts=(--db "$DBNAME" --out "$BACKUP_PATH")
41+
if [ -n "${MONGO_USER:-}" ]; then
42+
dump_opts+=(--username "$MONGO_USER")
43+
fi
44+
if [ -n "${MONGO_PASS:-}" ]; then
45+
dump_opts+=(--password "$MONGO_PASS")
46+
fi
47+
3048
# Dump the database
31-
mongodump --db "$DBNAME" --username "$USERNAME" --password "$PASSWORD" --out "$BACKUP_PATH"
49+
mongodump "${dump_opts[@]}"
3250

3351
# Stop mongod if we started it
3452
if [ "$started_mongod" = true ]; then

0 commit comments

Comments
 (0)