Issue
I have setup environment variables for to access MongoDB database. All works except for the MongoDB connection string which is pretty long.
Mongodb string can be provided in different format,
mongodb://myDBReader:D1fficultP%[email protected]:27017/?authSource=admin
Other examples are here - https://www.fosslinux.com/50317/connection-string-in-mongodb-with-examples.htm
In my case the string was provided by the database admin, so I am using it as it is provided. All, the environmental variables are shown at it is in .bashrc
file except the MONGODB connection string. If I use the string from within my python script it works well, but when I call it through environment variables (.bashrc file) something changes the string.
Setup on .bashrc
export MGDB_CON_STRING="mongodb://myMGDB:someuname....................server/dbname?authSource=$external&authMechanism=PLAIN....."
When this variable is called by python script as
mgdb_con_str = os.environ["MGDB_CON_STRING"]
something is eating up the text $external&
to be exact) in this string and returning it as
"mongodb://myMGDB:someuname....................server/dbname?authSource=authMechanism=PLAIN....."
However, if I override this variable again by using it within python script it works
mgdb_con_str = r"mongodb://myMGDB:someuname....................server/dbname?authSource=$external&authMechanism=PLAIN....."
- so this works
Something is eating that $external&
within the string and I cannot find what exactly is causing this. I also cannot find any question related to this problem elsewhere on stack or general google search. But, string value of all other environment variables do not change. And, similar problem arises if I read the mongodb string through config file.
Solution
One other way to handle this situation is to use single quotes when preparing the environment variables and it work bash and csh scripts.
Instead of this
export MGDB_CON_STRING="mongodb://myMGDB:someuname....................server/dbname?authSource=$external&authMechanism=PLAIN....."
Do this
export MGDB_CON_STRING='mongodb://myMGDB:someuname....................server/dbname?authSource=$external&authMechanism=PLAIN.....'
When this variable is called by python script as
mgdb_con_str = os.environ["MGDB_CON_STRING"]
print(mgdb_con_str)
# returns the raw string
'mongodb://myMGDB:someuname....................server/dbname?authSource=$external&authMechanism=PLAIN.....'
Answered By - everestial007 Answer Checked By - David Marino (WPSolving Volunteer)