mongo intialization script
This commit is contained in:
parent
8216a859ad
commit
eec93f7e12
1 changed files with 52 additions and 0 deletions
52
lxc1/p2-apps/mongo/mongo_init.sh
Normal file
52
lxc1/p2-apps/mongo/mongo_init.sh
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
#!/bin/bash
|
||||
# Move to the script's directory
|
||||
cd "$(dirname "$0")"
|
||||
|
||||
# 1. ROBUST ENV SOURCING (Same logic as MinIO/Keepalived)
|
||||
ENV_PATH="/docker/mongo/.env"
|
||||
if [ -f "$ENV_PATH" ]; then
|
||||
while read -r line || [ -n "$line" ]; do
|
||||
[[ "$line" =~ ^#.*$ ]] && continue
|
||||
[[ -z "$line" ]] && continue
|
||||
export "${line//\"/}"
|
||||
done < "$ENV_PATH"
|
||||
else
|
||||
echo "ERROR: .env file not found!"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# 2. WAIT FOR MONGO TO BE READY
|
||||
# We need the container to be up before we can run mongosh commands
|
||||
echo "⏳ Waiting for MongoDB container (${KOMODO_DB_HOSTNAME}) to be ready..."
|
||||
MAX_RETRIES=10
|
||||
COUNT=0
|
||||
until docker exec "$KOMODO_DB_HOSTNAME" mongosh --quiet --eval "db.adminCommand('ping')" &>/dev/null; do
|
||||
((COUNT++))
|
||||
if [ $COUNT -ge $MAX_RETRIES ]; then
|
||||
echo "❌ Timeout: MongoDB container is not responding."
|
||||
exit 1
|
||||
fi
|
||||
sleep 2
|
||||
done
|
||||
|
||||
# 3. CHECK-THEN-INITIATE LOGIC
|
||||
# Ask the DB if it is already part of a replica set
|
||||
IS_INIT=$(docker exec -t "$KOMODO_DB_HOSTNAME" mongosh --quiet --eval "rs.status().ok" 2>/dev/null)
|
||||
|
||||
if [ "$IS_INIT" == "1" ]; then
|
||||
echo "✅ MongoDB Replica Set 'rs${LXC_NUM}' is already initialized. Skipping."
|
||||
else
|
||||
echo "⚠️ Replica Set not found. Initializing 'rs${LXC_NUM}' now..."
|
||||
|
||||
# Use your defined PRI/SEC variables for the members
|
||||
docker exec -t "$KOMODO_DB_HOSTNAME" mongosh --eval "
|
||||
rs.initiate({
|
||||
_id: 'rs${LXC_NUM}',
|
||||
members: [
|
||||
{ _id: 0, host: '${KOMODO_DB_PRI}:27017' },
|
||||
{ _id: 1, host: '${KOMODO_DB_SEC}:27017' }
|
||||
]
|
||||
})"
|
||||
|
||||
echo "🚀 Initialization command sent! Transitioning to Primary..."
|
||||
fi
|
||||
Loading…
Reference in a new issue