I am developing Rails v2.3 app. and using MySQL v5.1 on Ubuntu machine.
I have a rake task to stop and start mysql database like following:
namespace :db do
task :some_db_task => :environment do
...
exec 'sudo /etc/init.d/mysql stop'
...
exec 'sudo /etc/init.d/mysql start'
end
end
As you see above in the code, I used sudo to make sure the command get executed. However, because of this sudo , when I run the rake task, there will be a prompt ask me to input root password though the rake task get run successfully.
I want to avoid the password input thing, so I thought I could execute shell command to firstly change to root user, then stop/start MySQL, so I changed my code to following:
namespace :db do
task :some_db_task => :environment do
...
exec 'sudo su'
exec '/etc/init.d/mysql stop'
...
exec '/etc/init.d/mysql start'
end
end
See, I added sudo su command to be run firstly. Now I run my rake task again, but, suprisingly the rake task run until exec 'sudo su' then it stopped, the rest code does not even get run. Why? How to get rid of it?
(Generally, I do not want to input root password during the rake task running for MySQL start and stop)
You have several problems.
First, the Kernel#exec method won’t return. See the API description:
Second, it’s really weird to execute
sudofrom Ruby. Could you simply executesudo rake db:some_db_task?UPDATED
Third,
Kernel#execwon’t return, butKernel#systemwill. If you really want tosudoin your rake script, you need to useKernel#systemand executesudoin every command. Ex:system 'sudo su'doesn’t work. It will start a shell with root user, and when you leave the shell, the Ruby process won’t gain root permission.