Search code examples
ruby-on-railsdeploymentcapistrano

Capistrano before/after hooks, use_sudo, something not working


I have the below config in my deploy.rb

before("deploy:cleanup") { set :use_sudo, true }
  after "deploy:restart", "deploy:cleanup"
after("deploy:cleanup") { set :use_sudo, false }

This is because some other factor in my setup creates files with a different user and I need to be able to clean them up. Elsewhere, I set it to false default.

The problem is, when I run deploy, I am not able to run cleanup, I am getting permissions errors, and I see the command generated as

ls -1dt /u/apps/MYAPP/releases/* | tail -n +6 |  xargs rm -rf

However, if i run deploy:cleanup directly it works just fine with the below command.

sudo -p 'sudo password: ' ls -1dt /u/apps/netprice/releases/* | tail -n +6 | sudo -p 'sudo password: ' xargs rm -rf

I am not sure if this is as expected, and I am understanding capistrano wrong, and if there is a cleaner (:P) way to achieve this?

I am using Rails 3.2 and capistrano 2.15


Solution

  • The reason your code does not work is because you are trying to set the wrong configuration key. The deploy:cleanup task uses internally the try_sudo method. If you see the source of that method you will notice that it executes the command based on the contents of run_method key instead of use_sudo.

    This means that if you change your code to set :run_method, :sudo (and then back to :run) you should get what you need.

    As a side note, the use_sudo key is actually used internally when capistrano boots to set the appropriate value to run_method