Search code examples
ruby-on-railsnginxpassengerzshrc

Phusion Passenger not reading .zshrc environment variables


I am using Phusion Passenger 5.1.8 and have set the following in my .zshrc

export SECRET_KEY_BASE='secure_key_base'
export DATABASE_NAME='db_production'
export DATABASE_PASSWORD='secure_db_pass'

I then did source ~/.zshrc and restart nginx with sudo service nginx restart. However, my application is complaining that it cannot find the SECRET_KEY_BASE and fails to start up. If I manually put these in config/secrets.yml then everything works well.

My config/secrets.yml has the following:

production:
  secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>

and my config/database.yml file has:

production:
  <<: *default
  database: <%= ENV['DATABASE_NAME'] %>
  password: <%= ENV['DATABASE_PASSWORD'] %>

Can someone please explain how I'd go about using zsh environment variables with Phusion Passenger?

Thanks!


Solution

  • So the problem is that you are using your environment variable in .zshrc and you run nginx from systemd. Both have no connection to each other.

    What you need is that your nginx should have these variable, which is run through a Systemd service. You need to use what is called a Drop-in

    mkdir -p /etc/systemd/system/nginx.service.d
    
    cat > /etc/systemd/system/nginx.service.d/90-nginx-myapp.conf <<EOF
    [Service]
    Environment=SECRET_KEY_BASE=XYZ
    Environment=SECRET_KEY_BASE2=XYZ2
    EnvironmentFile=-/etc/myapp/environment
    EOF
    

    You can either use Environment= to declare a variable. Or you can use a file with environment variables.

    Once you have added the drop-in, you need to reload systemd

    $ systemctl daemon-reload
    $ systemctl status nginx
    ● nginx.service - A high performance web server and a reverse proxy server
       Loaded: loaded (/lib/systemd/system/nginx.service; disabled; vendor preset: enabled)
      Drop-In: /etc/systemd/system/nginx.service.d
               └─90-nginx-myapp.conf
       Active: inactive (dead)
    

    And then use systemctl restart nginx

    Now nginx should get the variables you want it to have.

    Edit-1

    If you need to use variables in both NGINX and your shell. The create a file with variables like beow

    SECRET_KEY_BASE=XYZ
    SECRET_KEY_BASE2=XYZ2
    

    In your drop-in use the EnvironmentFile= and in your .bashrc or .bash_profile or .zshrc add the below lines

    # set -a will make sure that X=Y is equivalent to export X=Y
    set -a
    source /etc/myapp/environment
    # disable auto export of variable
    set +a