Ali Zain Ali Zain - 4 months ago 8x
Ruby Question

Unable to Access ENV variable in rails

I am trying to use env variables in my rails app and set those variable values in ubuntu 14.04

I tried setting using export command

export mongodb_username="abc"
export mongodb_password="cde"

and also tried setting them in /etc/environment and in ~/.bashsrc

and printenv gives following results

>> printenv mongodb_username
=> abc
>> printenv mongodb_password
=> cde

BUT in RAILS APP or irb the output is following

>> ENV['mongodb_password']
=> nil
>> ENV['mongodb_username']
=> nil

I am missing something? Please help!!!


When setting an environment variable's value using export, that value is available only in the shell in which it was set, and its subshells. So you'll need to export those variables in every shell in which you need them.

However, you can automate this, of course.

If you have variables that you need frequently, one approach is to put their assignments in a shell script and then source the shell script in any shells you need them in (see for more on this).

If it's ok to have the variables be in effect in all your shells, then a simpler way is to export them from your startup script (probably ~/.bashrc).