简体   繁体   中英

execute 'sudo su' command in rake task

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:

Replaces the current process by running the given external command.

Second, it's really weird to execute sudo from Ruby. Could you simply execute sudo rake db:some_db_task ?

UPDATED

Third, Kernel#exec won't return, but Kernel#system will. If you really want to sudo in your rake script, you need to use Kernel#system and execute sudo in every command. Ex:

   system 'sudo /etc/init.d/mysql stop'
   system 'sudo /etc/init.d/mysql start'

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.

I would recommend creating shell aliases for the two commands instead. Rake tasks in Rails were not really intended to do system specific things.

Add these lines to your .bashrc to make it quicker to start and stop.

alias mysql_start = 'sudo /etc/init.d/mysql start'
alias mysql_stop = 'sudo /etc/init.d/mysql stop'

If you're looking to do this as a deployment type of situation, capistrano is better suited for the work.

I think you should use sudo for rake not for custom command (ie sudo rake db:some_db_task)? or try call exec 'sudo su' first time, other executable without 'sudo', but i think rake can run exec every time for new session and sudo su command was closed on next exec.

Some link about this problem http://www.ruby-forum.com/topic/69967

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM