Reputation: 1032
Here is my database configuration file
default: &default
adapter: mysql2
encoding: utf8
pool: 5
production:
<<: *default
host: localhost
database: demo_production
username: demo
password: demo
I do not want to check-in my database configuration for production environment, I want to load it through an external file
How to do this in rails 4?
Upvotes: 1
Views: 1730
Reputation: 1032
You can load database configurations using environment variables just like this:
default: &default
adapter: mysql2
encoding: utf8
pool: 5
production:
<<: *default
host: <%= ENV['PROD_DB_HOST'] %>
database: <%= ENV['PROD_DB'] %>
username: <%= ENV['PROD_USER'] %>
password: <%= ENV['PROD_USER_PASS'] %>
If you look at the code, we have embed ruby code in the YML file. When rails executes this, it looks for the environment variables. The environment variables can be set through UNIX shell or through some ruby program or a YML file. You have to make sure that the environment variables are set before database.yml is executed.
Method 1: If you are setting up the environment variables in UNIX, export the variables before you start the rails server.
export PROD_DB_HOST = "my_host"
export PROD_DB = "my_production_db"
export PROD_USER = "my_prod_user"
export PROD_USER_PASS = "my_password"
Method 2: You could also set them through an external file and load it in the rails application. Let us see how to set through some ruby program
#overrides.rb
# db configuration
ENV['PROD_DB_HOST'] = 'my_host'
ENV['PROD_DB'] = 'my_production_db'
ENV['PROD_USER'] = 'my_prod_user'
ENV['PROD_USER_PASS'] = 'my_password'
Now the final step, how to load the files in rails application?
Rails load the configuration files in the following order
So, you have to load the external config file before rails executes the 'config/database.yml'.
'boot.rb' and 'application.rb' contains your application configurations. I don't want to touch that. I prefer loading the the config file in 'environments/.rb'. Append this line at the end of file.
# File: 'config/environments/production.rb'
# Load external configuration
load '/etc/prod_env/overrides.rb', :if_exists? => true
path could be anything,i have placed my file in '/etc/prod_env/'.
Upvotes: 3