Skip to content

Commit 118f2a5

Browse files
committed
Improve secret handling for MongoDB backups
1 parent 2afb17c commit 118f2a5

File tree

2 files changed

+78
-0
lines changed

2 files changed

+78
-0
lines changed

README.md

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -30,3 +30,27 @@ python src/run.py --help
3030
```
3131

3232
for a description of all available options.
33+
34+
## MongoDB backup script
35+
36+
`scripts/backup_mongodb.sh` dumps a MongoDB database to a Dropbox-synced
37+
folder. The script starts `mongod` if it is not running and stops it again
38+
when the backup finishes (if it was started by the script).
39+
40+
Make it executable before scheduling it with `cron`:
41+
42+
```bash
43+
chmod +x scripts/backup_mongodb.sh
44+
```
45+
46+
Store credentials in environment variables rather than editing the script.
47+
You may create a file named `~/.mongodb_backup_env` with content like:
48+
49+
```bash
50+
export DBNAME=mydb
51+
export MONGO_USER=myuser
52+
export MONGO_PASS=mypassword
53+
```
54+
55+
The backup script will source this file if present.
56+

scripts/backup_mongodb.sh

Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
#!/bin/bash
2+
# scripts/backup_mongodb.sh
3+
# Backup MongoDB database, ensuring mongod is running.
4+
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+
# Require credentials via environment variables
15+
: "${DBNAME:?Set DBNAME, e.g., export DBNAME=your_db}"
16+
: "${MONGO_USER:?Set MONGO_USER, e.g., export MONGO_USER=username}"
17+
: "${MONGO_PASS:?Set MONGO_PASS, e.g., export MONGO_PASS=password}"
18+
19+
DATE=$(date +%Y-%m-%d)
20+
BACKUP_DIR="$HOME/Dropbox/backups"
21+
BACKUP_PATH="$BACKUP_DIR/db_backup_${DATE}"
22+
23+
mkdir -p "$BACKUP_DIR"
24+
25+
# Track whether we started mongod
26+
started_mongod=false
27+
28+
# Check if mongod process is running
29+
if pgrep mongod >/dev/null; then
30+
echo "mongod is running"
31+
else
32+
echo "mongod is not running. Starting..."
33+
if command -v systemctl >/dev/null; then
34+
sudo systemctl start mongod
35+
else
36+
sudo service mongod start
37+
fi
38+
started_mongod=true
39+
fi
40+
41+
# Dump the database
42+
mongodump --db "$DBNAME" \
43+
--username "$MONGO_USER" --password "$MONGO_PASS" \
44+
--out "$BACKUP_PATH"
45+
46+
# Stop mongod if we started it
47+
if [ "$started_mongod" = true ]; then
48+
echo "Stopping mongod..."
49+
if command -v systemctl >/dev/null; then
50+
sudo systemctl stop mongod
51+
else
52+
sudo service mongod stop
53+
fi
54+
fi

0 commit comments

Comments
 (0)