@@ -78,7 +78,7 @@ if [ ! -f "$MONGO_KEYFILE" ]; then
78
78
chown mongodb:mongodb " $MONGO_KEYFILE "
79
79
fi
80
80
81
- # NOTE: Update mongod.conf.
81
+ # NOTE: First create a MongoDB config without authentication
82
82
cat << EOF | sudo tee $MONGO_CONF
83
83
storage:
84
84
dbPath: /var/lib/mongodb
@@ -89,9 +89,6 @@ systemLog:
89
89
net:
90
90
port: $MONGO_PORT
91
91
bindIp: 127.0.0.1
92
- security:
93
- authorization: enabled
94
- keyFile: $MONGO_KEYFILE
95
92
replication:
96
93
replSetName: $REPLICA_SET
97
94
EOF
@@ -112,7 +109,46 @@ if [ "$ROLE" == "primary" ]; then
112
109
fi
113
110
114
111
# NOTE: Create admin user.
115
- mongosh --port $MONGO_PORT --eval " db.getSiblingDB('admin').createUser({ user: '$DB_USERNAME ', pwd: '$DB_PASSWORD ', roles: [ { role: 'root', db: 'admin' } ] })" || echo " Admin user may already exist."
112
+ echo " Creating admin user..."
113
+ if mongosh --port $MONGO_PORT --eval " db.getSiblingDB('admin').createUser({ user: '$DB_USERNAME ', pwd: '$DB_PASSWORD ', roles: [ { role: 'root', db: 'admin' } ] })" ; then
114
+ echo " ✅ Admin user created successfully"
115
+ else
116
+ echo " ❌ Failed to create admin user"
117
+ exit 1
118
+ fi
119
+
120
+ # NOTE: Now update the config to enable authentication
121
+ echo " Enabling authentication in MongoDB configuration..."
122
+ cat << EOF | sudo tee $MONGO_CONF
123
+ storage:
124
+ dbPath: /var/lib/mongodb
125
+ systemLog:
126
+ destination: file
127
+ path: $LOG_FILE
128
+ logAppend: true
129
+ net:
130
+ port: $MONGO_PORT
131
+ bindIp: 127.0.0.1
132
+ security:
133
+ authorization: enabled
134
+ keyFile: $MONGO_KEYFILE
135
+ replication:
136
+ replSetName: $REPLICA_SET
137
+ EOF
138
+
139
+ # Restart MongoDB with authentication enabled
140
+ echo " Restarting MongoDB with authentication enabled..."
141
+ sudo systemctl restart mongod
142
+ sleep 5
143
+
144
+ # Verify we can connect with authentication
145
+ echo " Verifying authentication..."
146
+ if mongosh --port $MONGO_PORT -u $DB_USERNAME -p $DB_PASSWORD --authenticationDatabase admin --eval " db.adminCommand('ping')" ; then
147
+ echo " ✅ Authentication working correctly"
148
+ else
149
+ echo " ❌ Authentication verification failed"
150
+ exit 1
151
+ fi
116
152
117
153
# NOTE: Setup log rotation.
118
154
cat << EOF | sudo tee /etc/logrotate.d/mongod
0 commit comments