Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails doesn't see environment variable

I am trying to move a Rails application into production but I am having a problem with Rails not seeing my environment variable.

I have the password for my database setup in my .bashrc file like

export APP_NAME_DATABASE_PASSWORD=secretkey

In irb

ENV["APP_NAME_DATABASE_PASSWORD"]

returns secretkey.

Using

RAILS_ENV=production rails c

and just

rails c

returns secretkey but when starting the application I get

Access is denied (using password: NO)

I am using a slightly modified version of the init script on "How To Deploy a Rails App with Unicorn and Nginx on Ubuntu 14.04" to start unicorn.

It is being hosted on Ubuntu Server 14.04.

like image 922
agustaf Avatar asked Apr 08 '16 20:04

agustaf


4 Answers

Try doing spring stop followed by rails c

Spring is a rails application preloader that loads the ENV configuration. It might not have loaded the .bashrc changes in your case.

like image 68
Raghav Jajodia Avatar answered Oct 31 '22 03:10

Raghav Jajodia


Or you forgot to install gem 'dotenv-rails' ¯_(ツ)_/¯

like image 23
dani24 Avatar answered Oct 31 '22 02:10

dani24


export APP_NAME_DATABASE_PASSWORD=secretkey is most likely scoping your environment variable to a bash process. Since Unicorn doesn't run as a child of bash process, it doesn't have access to this environment variable.

I'd recommend storing your ENV vars in a single place, such as application.yml and loading them into your ruby environment at the start of your application. There are some great tools that do this. I'd recommend looking into Figaro: https://github.com/laserlemon/figaro.

Here's another post relevant to your question: Re-source .bashrc when restarting unicorn?

like image 35
Anthony E Avatar answered Oct 31 '22 04:10

Anthony E


I had a similar problem. A simple solution for you would be to run:

export RAILS_ENV=production && rails c

The reason is that when you do not use the export, the rails can not see the environment variable but you see its value when you execute echo on the console.

like image 24
Marcel Bezerra Avatar answered Oct 31 '22 02:10

Marcel Bezerra