« Drawn to the Mike | Main | Erlang Blogging Contest »

April 30, 2007

Prompting for Rails Database Password

Mike and I are running a Rails Studio in Denver. We were talking about database configuration, and an attendee asked "How can I make Rails prompt me for the database password, rather than hard code it into a configuration file?" It turns out that's easy to do, because the Rails configuration files are processed through the ERb templating system.

Here's what the production stanza looks like in the default database.yml file:

production:
  adapter: mysql
  database: events_production
  username: root
  password: 

If we want to prompt at the console for a password, we can change it like this:

<%
  def get_password
      print "Password: "
      `stty -echo`
      STDIN.gets.chomp ensure `stty echo`
  end
%>
production:
  adapter: mysql
  database: events_production
  username: root
  password: <%= get_password %>

Now, when Rails reads the configuration file, it gets to the password field and discovers it needs to run the get_password method. We define that method in the code block between <% and %>. This prompts for the password (with no echo--this only works on Unix boxes).

Does this really work in production: I don't know. It seems to, but I haven't tested it exhaustively.

TrackBack

TrackBack URL for this entry:
http://www.typepad.com/t/trackback/2226312/18117344

Listed below are links to weblogs that reference Prompting for Rails Database Password:

Comments

Thanks, PragDave! It had nothing to do with passwords in my case, but your exposition of the config - yaml - erb connection just broke a huge logjam for me and saved me a ton of parser writing and dsl wheel reinvention.

I have also done things like putting passwords in a file and then running crypt it. (vi -x etc.) then before the script is started, it asks for the decrypt password and all relevant info can be decrypted. You could do the same in ruby and when rails start you could supply the password on the startup commandline..

not bulletproof but it puts another layer of protection.

Ooh! I like the use of line-modifying ensure. (Assuming Kernel#` is guaranteed not to raise.)

Post a comment

If you have a TypeKey or TypePad account, please Sign In

Now in Beta

  • Programming Ruby, 3rd Edition
    Third Edition, Covering Ruby 1.9, now in beta
My Photo

Pragmatic Stuff

Photos

  • www.flickr.com
    This is a Flickr badge showing public photos from pragdave tagged with pragdave_badge. Make your own badge here.

Site Search

  • Google Search

    The web
    PragDave