How to Run Shell Commands on Server in Capistrano V3

How to run shell commands on server in Capistrano v3?

In Capistrano v3, you must specify where you want to run the code by calling on with a list of hostnames, e.g.

task :execute_on_server do
on "root@example.com" do
execute "some_command"
end
end

If you have roles set up, you can use the roles method as a convenience:

role :mailserver, "root@mail.example.com"

task :check_mail do
on roles(:mailserver) do
execute "some_command"
end
end

There is some v3 documentation here: http://www.capistranorb.com/

How to execute a command on the server with Capistrano?

You want to use script/runner. It starts an instance of the app to execute the method you want to call. Its slow though as it has to load all of your rails app.

~/user/mysite.com/current/script/runner -e production FeedEntry.update_all 2>&1

You can run that from the capistrano task.

Capistrano 3: bundler not recognized when running custom shell command

Generally RVM is initialized only in a login shell, so capistrano commands are unaware of RVM. Simply change your shell command to fix this:

# play nice with rvm
set :default_shell, '/bin/bash -l'

Capistrano 3 execute arbitrary command on remote server

I suggest to write your own little rake task to do it. Use readline gem
First of all thanks to follow materials:

  1. https://thoughtbot.com/blog/tab-completion-in-gnu-readline-ruby-edition

  2. How to write a Ruby command line app that supports tab completion?


desc "Remote console"
task :console do
require 'readline'
# https://thoughtbot.com/blog/tab-completion-in-gnu-readline-ruby-edition

host_args = (ENV['HOSTS'] || '').split(',').map { |r| r.to_sym }
role_args = (ENV['ROLES'] || '').split(',').map { |r| r.to_sym }

LIST = `ls /usr/bin`.split("\n").sort + `ls /bin`.split("\n").sort

comp = proc { |s| LIST.grep(/^#{Regexp.escape(s)}/) }

Readline.completion_append_character = " "
Readline.completion_proc = comp

while line = Readline.readline('cap> ', true)
begin
next if line.strip.empty?
exec_cmd(line, host_args, role_args)
rescue StandardError => e
puts e
puts e.backtrace
end
end
end

def exec_cmd(line, host_args, role_args)
line = "RAILS_ENV=#{fetch(:stage)} #{line}" if fetch(:stage)
cmd = "bash -lc '#{line}'"
puts "Final command: #{cmd}"
if host_args.any?
on hosts host_args do
execute cmd
end
elsif role_args.any?
on roles role_args do
execute cmd
end
else
on roles :all do
execute cmd
end
end
end

And do what you want with it, cheers! =))

To use bash --login by default with capistrano 3 + sshkit + rvm

you can not use rvm use from scripts - unless you source rvm first like you did with the prefix,

but you can use rvm ... do ... in scripts without sourcing:

execute :rvm, "#{ Configs.rvm.ruby }@#{ Configs.rvm.gemset }", "--create", :do, :true


Related Topics



Leave a reply



Submit