Search code examples
rubysinatraenvironment-variablesubuntu-server

sinatra app can't find environmental variable but test script can


I'm using the presence of an environmental variable to determine if my app is deployed or not (as adversed to running on my local machine).

My test script can find and display the variable value but my according to my app the variable isn't present.

test.rb

Secret_Key_Path = ENV['APPLICATION_VERSION'] ? '/path/to/encrypted_data_bag_secret' : File.expand_path('~/different/path/to/encrypted_data_bag_secret')
puts ENV['APPLICATION_VERSION']
puts Secret_Key_Path
puts File.exists? Secret_Key_Path

info.rb (the relevant bit)

::Secret_Key_Path = ENV['APPLICATION_VERSION'] ? '/path/to/encrypted_data_bag_secret' : File.expand_path('~/different/path/to/encrypted_data_bag_secret')

If I log the value of Secret_Key_Path it logs as the value I don't expect (i.e. '~/different/path/to/encrypted_data_bag_secret' instead of '/path/to/encrypted_data_bag_secret')

Here's how I start my app (from inside of my main executable script, so I can just run app install from any where instead of having to go to the folder)

exec "(cd /path/to/app/root && exec sudo rackup --port #{80} --host #{'0.0.0.0'} --pid /var/run/#{NAME}.pid -O NAME[#{NAME}] -D)"

if I do env | grep APP I get:

APPLICATION_VERSION=1.0.130
APPLICATION_NAME=app-name

It was suggested that it was an execution context problem but I'm not sure how to fix that if it were that.

So Whats going on? Any help & suggestion would be appreciated.


Solution

  • You can keep your environment variables with sudo by using the -E switch:

    From the manual:

    -E, --preserve-env Indicates to the security policy that the user wishes to preserve their existing environment variables. The security policy may return an error if the user does not have permission to preserve the environment.

    Example:

    $ export APPLICATION_VERSION=1.0.130
    $ export APPLICATION_NAME=app-name
    

    Check the variables:

    $ sudo -E env | grep  APP
    

    and you should get the output:

    APPLICATION_NAME=app-name
    APPLICATION_VERSION=1.0.130
    

    Also if you want to keep variables permanently keeped you can add to the /etc/sudoers file:

    Defaults env_keep += "APPLICATION_NAME APPLICATION_VERSION"