How can I pass environment variables to mongo docker-entrypoint-initdb.d? How can I pass environment variables to mongo docker-entrypoint-initdb.d? docker docker

How can I pass environment variables to mongo docker-entrypoint-initdb.d?


you can make use of a shell script to retrieve env variables and create the user.

initdb.d/init-mongo.sh

set -emongo <<EOFuse $MONGO_INITDB_DATABASEdb.createUser({  user: '$MONGO_INITDB_USER',  pwd: '$MONGO_INITDB_PWD',  roles: [{    role: 'readWrite',    db: '$MONGO_INITDB_DATABASE'  }]})EOF

docker-compose.yml

version: "3.7"services:  mongodb:    container_name: "mongodb"    image: mongo:4.4    hostname: mongodb    restart: always    volumes:      - ./data/mongodb/mongod.conf:/etc/mongod.conf      - ./data/mongodb/initdb.d/:/docker-entrypoint-initdb.d/      - ./data/mongodb/data/db/:/data/db/    environment:      - MONGO_INITDB_ROOT_USERNAME=root      - MONGO_INITDB_ROOT_PASSWORD=root      - MONGO_INITDB_DATABASE=development      - MONGO_INITDB_USER=mongodb      - MONGO_INITDB_PWD=mongodb    ports:      - 27017:27017    command: [ "-f", "/etc/mongod.conf" ]

Now you can connect to development database using mongodb as user and password credentials.


Use shell script (e.g mongo-init.sh) to access variables. Can still run JavaScript code inside as below.

set -emongo <<EOFuse admindb.createUser({  user: '$MONGO_ADMIN_USER',  pwd:  '$MONGO_ADMIN_PASSWORD',  roles: [{    role: 'readWrite',    db: 'dummydb'  }]})EOF

Shebang line is not necessary at the beginning as this file will be sourced.


You can use envsubs.If command not found : here. Install it on your runners host if you use shell runners, else, within the docker image used by the runner, or directly in your script.

(NB: Your link isn't free, so I can't adapt to your situation :p )

Example:

init.js.template:

console.log('$GREET $PEOPLE $PUNCTUATION')console.log('Pipeline from $CI_COMMIT_BRANCH')

gitlab_ci.yml:

variables:  GREET: "hello"  PEOPLE: "world"  PUNCTUATION: "!"# ...script:  - (envsubst < path/to/init.js.template) > path/to/init.js  - cat path/to/init.js

Output:

$ (envsubst < init.js.template) > init.js$ cat init.jsconsole.log('hello world !')console.log('Pipeline from master')