Last active
September 27, 2022 05:10
-
-
Save luketn/1efe282d8e3104c052daca3b1c616547 to your computer and use it in GitHub Desktop.
Start MongoDB docker image as a replica set
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/sh | |
# Map input values from the GitHub Actions workflow to shell variables | |
MONGODB_VERSION="6.0" | |
MONGODB_REPLICA_SET="test-rs" | |
MONGODB_PORT="27017" | |
MONGO_CMD="mongosh" # for earlier versions use "mongo" | |
if [ -z "$MONGODB_VERSION" ]; then | |
echo "" | |
echo "Missing MongoDB version in the [mongodb-version] input. Received value: $MONGODB_VERSION" | |
echo "" | |
exit 2 | |
fi | |
echo "::group::Starting MongoDB as single-node replica set" | |
echo " - port [$MONGODB_PORT]" | |
echo " - version [$MONGODB_VERSION]" | |
echo " - replica set [$MONGODB_REPLICA_SET]" | |
echo "" | |
docker run --name mongodb --publish $MONGODB_PORT:$MONGODB_PORT --detach mongo:$MONGODB_VERSION --replSet $MONGODB_REPLICA_SET --port $MONGODB_PORT | |
echo "::endgroup::" | |
echo "::group::Waiting for MongoDB to accept connections" | |
sleep 1 | |
TIMER=0 | |
until docker exec --tty mongodb $MONGO_CMD --port $MONGODB_PORT --eval "db.serverStatus()" # &> /dev/null | |
do | |
sleep 1 | |
echo "." | |
TIMER=$((TIMER + 1)) | |
if [[ $TIMER -eq 20 ]]; then | |
echo "MongoDB did not initialize within 20 seconds. Exiting." | |
exit 2 | |
fi | |
done | |
echo "::endgroup::" | |
echo "::group::Initiating replica set [$MONGODB_REPLICA_SET]" | |
docker exec --tty mongodb $MONGO_CMD --port $MONGODB_PORT --eval " | |
rs.initiate({ | |
\"_id\": \"$MONGODB_REPLICA_SET\", | |
\"members\": [ { | |
\"_id\": 0, | |
\"host\": \"localhost:$MONGODB_PORT\" | |
} ] | |
}) | |
" | |
echo "Success! Initiated replica set [$MONGODB_REPLICA_SET]" | |
echo "::endgroup::" | |
echo "::group::Checking replica set status [$MONGODB_REPLICA_SET]" | |
docker exec --tty mongodb $MONGO_CMD --port $MONGODB_PORT --eval " | |
rs.status() | |
" | |
echo "::endgroup::" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment