How do I see the ENV vars in a Rails app? - ruby-on-rails

I am taking over an old Rails app. No one has touched it in a year. The last developer left in April of 2015 and I have no way to contact him. I do have ssh access to the server, and I have access to the Github repo.
I don't know any of the usernames/passwords.
If I ssh to the server and I cat the database.yml file, I see stuff like:
staging:
adapter: mysql2
encoding: utf8
pool: 5
socket: /var/lib/mysql/mysql.sock
database: o_wawa_stage
username: wawa_stage
password: <%= ENV['STAGE_DATABASE_PASSWORD'] %>
host: access.dmedia.com
If I run the "printenv" command then I don't see any of these vars. I assume they are only loaded by the Rails environment.
I guess I can edit the templates to spit out the values with a bunch of "put" statements, but I'm thinking there must be a more obvious way to do this, other than printing the data where the public could see it?
If I try to run "rails console" I get:
Rails Error: Unable to access log file. Please ensure that /var/www/haha/production/releases/20150118213616/log/development.log exists and is writable (ie, make it writable for user and group: chmod 0664 /var/www/haha/production/releases/20150118213616/log/development.log). The log level has been raised to WARN and the output directed to STDERR until the problem is fixed.
I don't have sudo on this box, so I can not address the error.

Assuming the staging environment, as your example points to. You'll want to load the console by prepending the RAILS_ENV environment variable to the rails console command.
RAILS_ENV=staging rails console
That should get you in. Once you're in, you can just access the ENV variable directly.
2.2.2 (main):0 > ENV
And that will dump out the environment variables for you. Note, your prompt may look different. If you want to access a specific value, such as the database password, you can:
2.2.2 (main):0 > ENV['STAGE_DATABASE_PASSWORD']

Within your app directory, simply launch the Rails Console:
rails c
Then at the prompt:
ENV
This will list all loaded environmental variables for whichever environment you last exported.
Sorry, after posting this, I realized that the author had already tried to use rails console with errors...but I am fairly sure this should always work. You can't ask for printenv or env within the console, you must use all caps "ENV"

yourapp/config/env.yml or application.yml etc...
Look for code that looks like
AWS_KEY_ID: blahblah23rkjewfojerflbah
AWS_SECRET_KEY_ID: blahblah2394082fkwejfoblah

Related

Rails Production - How to set Secret Key Base?

So I am trying to get my rails app to deploy in production mode, but I get the error: Missing secret_token and secret_key_base for 'production' environment, set these values in config/secrets.yml
My secrets.yml file is as expected:
development:
secret_key_base: xxxxxxx
test:
secret_key_base: xxxxxxx
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
But even after google and research, I have no idea what to do with the production secret key base. Most of the info out there assumes I have certain background knowledge, but the reality is that I'm a noob.
Can anyone explain to me how to set my secret key and get this to work in production mode?
You can generate the key by using following commands
$ irb
>> require 'securerandom'
=> true
>> SecureRandom.hex(64)
=> "3fe397575565365108556c3e5549f139e8078a8ec8fd2675a83de96289b30550a266ac04488d7086322efbe573738e7b3ae005b2e3d9afd718aa337fa5e329cf"
>> exit
The errors you are getting just indicate that the environment variable for secret_key_base are not properly set on the server.
You can use various scripts like capistrano that automate the process of setting these before the application is run.
As for a quick fix try this:
export SECRET_KEY_BASE=YOUR SECRET BASE
Validate the environment variables and check if these have been set.
Command:
env | grep -E "SECRET_TOKEN|SECRET_KEY_BASE"
If your values pop up then these are set on the production server.
Also it is best practice to use ENV.fetch(SECRET_KEY) as this will raise an exception before the app even tries to start.
This answer helped me a lot. He indicates you how to config the secrets.yml file in production and how to read it from the environment:
original link:
https://stackoverflow.com/a/26172408/4962760
I had the same problem and I solved it by creating an environment
variable to be loaded every time that I logged in to the production
server and made a mini guide of the steps to configure it:
https://gist.github.com/pablosalgadom/4d75f30517edc6230a67
I was using Rails 4.1 with Unicorn v4.8.2, when I tried to deploy my
app it didn't start properly and in the unicorn.log file I found this
error message:
"app error: Missing secret_key_base for 'production' environment, set
this value in config/secrets.yml (RuntimeError)"
After some research I found out that Rails 4.1 changed the way to
manage the secret_key, so if you read the secrets.yml file located at
[exampleRailsProject]/config/secrets.yml you'll find something like
this:
Do not keep production secrets in the repository,
instead read values from the environment. production: secret_key_base: <%= ENV["SECRET_KEY_BASE"] %> This means that rails
recommends you to use an environment variable for the secret_key_base
in your production server, in order to solve this error you should
follow this steps to create an environment variable for Linux (in my
case Ubuntu) in your production server:
1.- In the terminal of your production server execute the next command:
$ RAILS_ENV=production rake secret This returns a large string with
letters and numbers, copy that (we will refer to that code as
GENERATED_CODE).
2.1- Login as root user to your server, find this file and edit it: $ vi /etc/profile
Go to the bottom of the file ("SHIFT + G" for capital G in VI)
Write your environment variable with the GENERATED_CODE (Press "i" key
to write in VI), be sure to be in a new line at the end of the file:
export SECRET_KEY_BASE=GENERATED_CODE Save the changes and close the
file (we push "ESC" key and then write ":x" and "ENTER" key for save
and exit in VI)
2.2 But if you login as normal user, lets call it example_user for this gist, you will need to find one of this other files:
$ vi ~/.bash_profile $ vi ~/.bash_login $ vi ~/.profile These files
are in order of importance, that means that if you have the first
file, then you wouldn't need to write in the others. So if you found
this 2 files in your directory "~/.bash_profile" and "~/.profile" you
only will have to write in the first one "~/.bash_profile", because
Linux will read only this one and the other will be ignored.
Then we go to the bottom of the file ("SHIFT + G" for capital G in VI)
And we will write our environment variable with our GENERATED_CODE
(Press "i" key to write in VI), be sure to be in a new line at the end
of the file:
export SECRET_KEY_BASE=GENERATED_CODE Having written the code, save
the changes and close the file (we push "ESC" key and then write ":x"
and "ENTER" key for save and exit in VI)
3.- You can verify that our environment variable is properly set in Linux with this command:
$ printenv | grep SECRET_KEY_BASE or with:
$ echo $SECRET_KEY_BASE When you execute this command, if everything
went ok, it will show you the GENERATED_CODE from before. Finally with
all the configuration done you should be able to deploy without
problems your Rails app with Unicorn or other.
When you close your shell terminal and login again to the production
server you will have this environment variable set and ready to use
it.
And thats it!! I hope this mini guide help you to solve this error.
Disclaimer: I'm not a Linux or Rails guru, so if you find something
wrong or any error I will be glad to fix it!
nowadays (rails 6) rails generate a secret key base in tmp/development_secret.txt for you.
and in production environment the best is having SECRET_KEY_BASE as en env variable, it will get picked up by rails.
you can check with Rails.application.secret_key_base.
should give you a long string of numbers and characters from 'a' to 'f' (a 128 chars long hexadecimal encoded string)
As you can see, there is a hardcoded value for the development and test environments, but the one for production comes from a variable. First of all, why this way? It is a security feature. This way, if you check this file into version control such as git or svn, the development and test values get shared, which is fine, but the production one (the one that would be used on a real website) isn't, so no one can look at the source to get that secret.
As for the variable used, ENV["SECRET_KEY_BASE"], this is an environment variable from the environment Rails is run in (not to be confused with the Rails "environment", such as development, test, and production). These environment variables come from the shell. As mentioned in JensD's post, you can set this environment variable temporarily with:
export SECRET_TOKEN=YOUR SECRET TOKEN
export SECRET_KEY_TOKEN=YOUR SECRET BASE
To generate a new secret token, use the rake secret command in the command line.
That is temporary, however, and not a good final solution. For a final solution, check out this article which has a quick bit near the end on implementing dotenv to load configuration secrets. Remember, if you use version control, be sure to exclude your .env file from being checked in!
Setting dotenv up takes a little bit of work, but I highly recommend it over trying to manually configure these environment variables.

bashrc environment variables not working with Rails app

I have setup variables in my ~/.bashrc file that I would like to use with my Rails app. The problem is Rails will not recognize these variables.
bashrc:
export MYSQL_DB_USERNAME=admin
export MYSQL_DB_PASSWORD=testing123
Rails app - database.yml
username: <%= ENV["MYSQL_DB_USERNAME"] %>
password: <%= ENV["MYSQL_DB_PASSWORD"] %>
If I go into the rails console and type:
ENV["MYSQL_DB_USERNAME"]
I get back: <= nil
I've reloaded my bashrc file and restarted the terminal. Neither worked. Why won't Rails read these variables from the bashrc file?
(I am using RVM for ruby version management, in case that matters).
Thanks.
You can put your setting at the top of ~/.bashrc.
Because mina uses ssh in non-interactive mode.
In the first files of .bashrc, it has
#If not running interactively, don't do anything
[ -z "$PS1" ] && return
The settings below this line will be ignored.
It depends on how you are running the rails app.
For example if you did
export MYSQL_DB_USERNAME=admin
export MYSQL_DB_PASSWORD=testing123
rails console
> ENV["MYSQL_DB_USERNAME"]
Then most likely your code would work. If you are starting the railsapp as a different user, or as a daemon/service, then it won't share the same environment and the environment variables you created won't be set anymore.
In my opinion, the best way to set variables is to create a yaml config file. You can do /etc/myapp/config.yml and inside it set the following
MYSQL_DB_USERNAME: admin
MYSQL_DB_PASSWORD: testing123
This should be more cleaner than storing the user_name/password inside your .bashrc file since you can allow only the rails user to reading this through file permissions - you don't want to play with the file permissions of your .bashrc.

rails secret_key_base not being recognized in production

So I am trying to deploy my rails app in production. When I go to the page I get a 500 error. When I go to my error logs I get the following error:
Exception RuntimeError in Rack application object (Missing `secret_key_base` for 'production' environment, set this value in `config/secrets.yml`)
I am running Rails 4.1 and my config/secrets.yml looks like this:
development:
secret_key_base: <development key>
test:
secret_key_base: <test key>
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
I ran rake secret to get the key and put the export in my bash_profile and sourced it. I ran rake assets:precompile successfully. Yet I still keep getting this error. Any ideas?
Update: I tried to update the error message provided to give slightly better information....and the message didn't update. I then tried adding the key directly to the yml file instead of using an environment variable and still no dice. Im running on hostmonster so I can't restart the server.....but something is telling me thats what needs to be done...
Update 2: After sleeping through the night it seems that this issue is no longer an issue. It must have been some sort of caching. Now my issue is that its trying to use an old config that i changed days ago for my database. If I figure out how to nullify the cache I will post it here and mark it as an answer. If someone else knows how to do it please let me know and I will mark it as an answer. I am using HostMonster as my hosting and followed the steps they have on their site for hosting my rails app.
I had the same problem and I solved creating an environment variable to be loaded every time that I login to the production server and made a mini guide of the steps to configure it by your self:
So I was using Rails 4.1 with Unicorn v4.8.2 and when I tried to deploy my app it doesn't start properly and into the unicorn.log file i found this error message:
app error: Missing secret_key_base for 'production' environment, set this value in config/secrets.yml (RuntimeError)
After a little research I found that Rails 4.1 change the way to manage the secret_key, so if we read the secrets.yml file located at exampleRailsProject/config/secrets.yml (you need to replace "exampleRailsProject" for your project name) you will find something like this:
# Do not keep production secrets in the repository,
# instead read values from the environment.
production:
secret_key_base: <%= ENV["SECRET_KEY_BASE"] %>
This means that rails recommends you to use an environment variable for the secret_key_base in our production server, so in order to solve this error you will need to follow this steps to create an environment variable for linux (in my case it is Ubuntu) in our production server:
1.- In the terminal of our production server you will execute the next command:
$ RAILS_ENV=production rake secret
This will give a large string with letters and numbers, this is what you need, so copy that (we will refer to that code as GENERATED_CODE).
2.1- Now if we login as root user to our server we will need to find this file and open it:
$ vi /etc/profile
Then we go to the bottom of the file ("SHIFT + G" for capital G in VI)
And we will write our environment variable with our GENERATED_CODE (Press "i" key to write in VI), be sure to be in a new line at the end of the file:
export SECRET_KEY_BASE=GENERATED_CODE
Having written the code we save the changes and close the file (we push "ESC" key and then write ":x" and "ENTER" key for save and exit in VI)
2.2 But if we login as normal user, lets call it example_user for this gist, we will need to find one of this other files:
$ vi ~/.bash_profile
$ vi ~/.bash_login
$ vi ~/.profile
These files are in order of importance, that means that if you have the first file, then you wouldn't need to write in the others. So if you found this 2 files in your directory "~/.bash_profile" and "~/.profile" you only will have to write in the first one "~/.bash_profile", because linux will read only this one and the other will be ignored.
Then we go to the bottom of the file ("SHIFT + G" for capital G in VI)
And we will write our environment variable with our GENERATED_CODE (Press "i" key to write in VI), be sure to be in a new line at the end of the file:
export SECRET_KEY_BASE=GENERATED_CODE
Having written the code we save the changes and close the file (we push "ESC" key and then write ":x" and "ENTER" key for save and exit in VI)
3.-We can verify that our environment variable is properly set in linux with this command:
$ printenv | grep SECRET_KEY_BASE
or with:
$ echo $SECRET_KEY_BASE
When you execute this command, if everything went ok, it will show you the GENERATED_CODE that we generated before. Finally with all the configuration done you can deploy without problems your Rails app with Unicorn or other.
Now when you close your shell terminal and login again to the production server you will have this environment variable set and ready to use it.
And Thats it!! I hope this mini guide help you to solve this error.
You need to restart your server, because after YourAppName::Application.initialize! called in config/environment.rb you can not change your settings.
Checkout your yml markup, probably there some errors
Probably something wrong in your config/initializers/secret_token.rb
The problem is not with ENV pseudo-hash. secret_key_base will be nil if in ENV no such a key.

Securely providing the database password in a Rails app

As you know, you MUST provide the correct database name, username, and password for the database in the config/database.yml file, or your Rails app will refuse to work.
In the default setup, your password is in plain text in the config/database.yml file. If your app is on a free GitHub repository, then your password is public information. This is not a viable option for a serious app. (It's OK for a tutorial exercise, provided that you don't use this password for anything else.)
I have a solution that has worked for me so far, but I'm wondering if there is something better. You can see my deployed example at https://github.com/jhsu802701/bsf .
What I do is set up the config/database.yml file to provide the username and password for the development environment programatically. For the development environment, I add commands to the config/database.yml script to acquire the development environment username (which is my regular username for the Debian Linux setup I use) and a blank password. (I give my username Postgres superuser privileges.) For the production environment, I add a command in the deployment script that acquires the username and password from files elsewhere on my account and writes this information to the config/database.yml file.
Is there a better solution?
Is there a Ruby gem that covers this? If not, I'm thinking of creating one.
The way that heroku does it, and a vast majority of other rails shops are with ENV variables
Export two variables to your environment,
export POSTGRES_USERNAME='username'
export POSTGRES_PASSWORD='password'
then in your database.yml file you can do
username: <%= ENV['POSTGRES_USERNAME'] %>
password: <%= ENV['POSTGRES_PASSWORD'] %>
This is how I make it work:
On terminal/cmd:
heroku config:set YOUR_DATABASE_PASSWORD=passywordy
Then, in /config/database.yml file;
production:
<<: *default
password: <%= ENV['YOUR_DATABASE_PASSWORD'] %>
(this password area is automatically generated when I used rails new my_app -d postgresql)
On other than heroku export you variables to system environment (linux) by typing in bash
export KEY=value
Then you can call it in Rails by ENV['KEY']
e.g.
in bash:
export CMS_DATABASE_PASSWORD=MySecurePassword
in secrets.yml:
password: <%= ENV['CMS_DATABASE_PASSWORD'] %>
Setting the environment variables as described in existing posts above, will only persist the environment variables for the duration of the current shell session.
To set the environment variables permanently, the export instruction(s) should be added to your shell config file. (Then run source ~/.bashrc to apply the changes to your current session)
TL;DR: If you're using BASH, add the export instruction(s) to ~/.bashrc.
While the above should suffice (if using BASH on most popular Linux distros), confidently identifying which config file to update for your shell can be quite tricky. The following post explains the reasons why and provides guidance on which config file to edit.
https://unix.stackexchange.com/questions/117467/how-to-permanently-set-environmental-variables

Failing to access environment variables within `database.yml` file

I have the following developement section of my development.yml file:
development:
adapter: postgresql
host: localhost
database: testtb
username: app_user
password: ENV['APP_USER_POSTGRES_PASSWORD'] <= Troublesome line
When I open a rails console via bundle exec rails console and type ENV['APP_USER_POSTGRES_PASSWORD'] I get back the DB password I've specified in my local profile. However, when I start my rails server, it can't connect to the DB, failing with
PGError FATAL: password authentication failed for user "app_user"
This was previously working when I had the DB password actually typed out in plain text, rather than trying to access it via ENV['...'], but for obvious reasons I want to keep the actual password out of this file entirely (and therefore out of the code repository) while still being able to commit other, non-secure changes to the database.yml file.
Is there something special about the syntax I'm missing, or are the environment variables for some reason not available when the database.yml file is being loaded?
Update: Some people report in the comments that this doesn't work as of Rails 4.2.x.x. I haven't tried it myself, so YMMV.
Ah, finally figured out the simple solution - it accepts embedded Ruby:
password: <%= ENV['APP_USER_POSTGRES_PASSWORD'] %>
Short and quick solution if you are running a Rails version > 4.2 Run the following command:
spring stop
..then run rails console or other rails command. My issue was that Spring server needed to be restarted in order to refresh/pickup my new ENV vars. I was starting up Rails console and it couldn't see them until I shut down Spring.
Previous versions of Rails didn't have this issue since they didn't use Spring server.
Another tool to help you troubleshoot -- Use the following command to print out your database.yml config. You can run it from the command line, but I prefer to run this within Rails console since then you can use awesome_print to make it pretty:
Within rails console:
puts ActiveRecord::Base.configurations
...or using awesome_print
ap ActiveRecord::Base.configurations
Or instead from the command line:
bin/rails runner 'puts ActiveRecord::Base.configurations'

Resources