Skip to content

Commit 76fc1ce

Browse files
committed
Make MongoDB backup credentials optional
1 parent 118f2a5 commit 76fc1ce

File tree

2 files changed

+16
-10
lines changed

2 files changed

+16
-10
lines changed

README.md

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -43,13 +43,14 @@ Make it executable before scheduling it with `cron`:
4343
chmod +x scripts/backup_mongodb.sh
4444
```
4545

46-
Store credentials in environment variables rather than editing the script.
47-
You may create a file named `~/.mongodb_backup_env` with content like:
46+
Store `DBNAME` (and optional credentials) in environment variables rather than
47+
editing the script. You may create a file named `~/.mongodb_backup_env` with
48+
content like:
4849

4950
```bash
5051
export DBNAME=mydb
51-
export MONGO_USER=myuser
52-
export MONGO_PASS=mypassword
52+
# export MONGO_USER=myuser
53+
# export MONGO_PASS=mypassword
5354
```
5455

5556
The backup script will source this file if present.

scripts/backup_mongodb.sh

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -11,10 +11,8 @@ if [ -f "$ENV_FILE" ]; then
1111
source "$ENV_FILE"
1212
fi
1313

14-
# Require credentials via environment variables
14+
# DBNAME is required; credentials are optional
1515
: "${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}"
1816

1917
DATE=$(date +%Y-%m-%d)
2018
BACKUP_DIR="$HOME/Dropbox/backups"
@@ -38,10 +36,17 @@ else
3836
started_mongod=true
3937
fi
4038

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+
4148
# Dump the database
42-
mongodump --db "$DBNAME" \
43-
--username "$MONGO_USER" --password "$MONGO_PASS" \
44-
--out "$BACKUP_PATH"
49+
mongodump "${dump_opts[@]}"
4550

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

0 commit comments

Comments
 (0)