#7. Setting environment variables for rails app in ubuntu

Never keep any secret data in public folder. Always use environment variables to keep secret data.

Suppose we want to set postgresql username and password as environment variables 

in Ubuntu then do as,

# type the following in the terminal to write in the .bashrc file.

echo 'export MY_POSTGRESQL_USERNAME="rajkumar"' >> ~/.bashrc

echo 'export MY_POSTGRESQL_PASSWORD="HJH34df@dff#@"' >> ~/.bashrc

reload .bashrc as,

source ~/.bashrc


In order to print environment variables prepend it with $ as, 
echo $MY_POSTGRESQL_USERNAME
echo $MY_POSTGRESQL_PASSWORD

test environment variables as,

echo $MY_POSTGRESQL_USERNAME

rajkumar

echo $MY_POSTGRESQL_PASSWORD

HJH34df@dff#@

Also use ubuntu command printenv to print all the environment variables.


then in the database.yml use these environment variables as,

development:

  adapter: postgresql

  encoding: unicode

  host: localhost

  username: <%= ENV["MY_POSTGRESQL_USERNAME"] %>

  password: <%= ENV["MY_POSTGRESQL_PASSWORD"] %>

  database: weblog_development

Another way to set environment variables using ruby ENV variable. Set project vise environment variables as key value pair. For Example,

Put a file in config/initializers. Set this file for gitignore.
write in the file as,
ENV["MY_POSTGRESQL_USERNAME"]  = 'rajkumar'

and read anywhere in the project as,
ENV["MY_POSTGRESQL_USERNAME"]


I personally prefer a gem for setting environment variables i.e. figaro

Comments

Popular posts from this blog

#6. Fetch time in rails

#8. nginx+puma deployment using capistrano