Search code examples
rubysshcapistranoresquecapistrano3

How to run Capistrano task locally from remote server?


Use case:
Suppose I have a Capistrano task defined, for example cap resque:start.
It takes :set values such as amount of workers from my deploy.rb.
Suppose I want to start resque workers on server reboot.
I can copypaste them to some post-reboot script, but if I change :set amount of workers or other configs, I'll need to change post-reboot script as well.

Instead of that, we can execute cap locally:resque:start in our post-reboot script, which will automatically take current amount of workers we set in deploy.rb.


Solution

    1. in Gemfile, add all Capistrano gems from :development to :production
    2. create a task cap locally:resque:start:

      namespace :locally do
        namespace :resque do
          task :start do
            run_locally { Rake::Task["resque:start"].execute }
          end
        end
      end
      
    3. add remote host to your authorized_keys on remote host (because Capistrano 3 requires stage set even if we are executing task locally. luckily ssh connection to localhost will be fast):

      1. ssh-keygen -t rsa
      2. cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
      3. chmod og-wx ~/.ssh/authorized_keys
    4. and now, on your remote production server, cap production locally:resque:start.