Incerteza
Incerteza

Reputation: 34884

Where to put environment variables on the server?

I have a Rails app on a production server and an .rb file where I do this:

Rails.configuration.my_sect = if Rails.env.development? || Rails.env.test?
  {
    secret_key: 'some_secrete',
    public_key: 'some_public'
  }
else
  {
    secret_key: ENV['key1'],
    public_key: ENV['key2']
  }
end

The application is on a Linux server. What's the best place to put the values of those secret_key and public_key on the server so ENV['key1'] and ENV['key2'] can always be accessible?

I don't want to use any gem or Capistrano.

Upvotes: 0

Views: 328

Answers (3)

mdesantis
mdesantis

Reputation: 8517

Even if you say you don't want to use any gem, I recommend you to use dotenv; even if it's not suggested to use it on a production environment.

Otherwise, the simplest plain solution is:

  1. create a per-project environment variables file (let's say "$PROJECT_DIR/.env")
  2. Add it to .gitignore
  3. execute it before the application server starting, with something like

    source "$PROJECT_DIR/.env" && rails server
    

But that's what dotenv is created for, so why reinvent the wheel?

Upvotes: 0

jljohnstone
jljohnstone

Reputation: 1230

Add /config/en_vars.rb to .gitignore

Create a file config/en_vars.rb and put your variables there:

ENV['key1']='foo'
ENV['key2']='bar'

Then in config/environment.rb add the lines below the require line:

en_vars = File.join(Rails.root, 'config/en_vars.rb')
load(en_vars) if File.exists?(en_vars)

Upvotes: 0

Leonid Shevtsov
Leonid Shevtsov

Reputation: 14179

I would put them in the server script, because, for example, shell configuration files like ~/.bashrc are not loaded in cron scripts or other scenarios.

The "server script" could be as simple as key1=foo key2=baz rails s.

Upvotes: 1

Related Questions