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.




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.
Posted by: clem | April 30, 2007 at 05:59 PM
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.
Posted by: Mike | May 02, 2007 at 11:09 AM
Ooh! I like the use of line-modifying ensure. (Assuming Kernel#` is guaranteed not to raise.)
Posted by: twifkak | May 29, 2007 at 05:32 AM