LoginSignup
9
4

More than 5 years have passed since last update.

capistrano3でのリモートコマンドの実行の仕方

Last updated at Posted at 2015-05-25

Capistrano2では、以下のような感じでベタ書きで書いていたりした。

namespace :deploy do
  task :link_html do
    run <<-CMD
      cd #{release_path}/public &&
      ln -nfs /opt/htdocs/hoge &&
      ln -nfs /opt/htdocs/foo &&
      ln -nfs /opt/htdocs/bar
    CMD
  end
end

Capistrano3ではSSHKitというライブラリを使って書けるようだ。
この辺りを参考に書いてみる。
- capistrano/sshkit
- sshkit/EXAMPLES.md at master · capistrano/sshkit

例をみるとwithinで対象ディレクトリにcdしてexecuteを実行してくれるようだ。
こんな感じで行けるだろうと思って書いてみる。

namespace :deploy do
  task :link_html => [:set_rails_env] do
    on roles(:web) do |host|
      within "#{release_path}/public" do
        execute "ln -nfs /opt/htdocs/hoge"
        execute "ln -nfs /opt/htdocs/foo"
        execute "ln -nfs /opt/htdocs/bar"
      end
    end
  end
end

リモートに入って確認するとホームディレクトリにhoge,foo,barが出来ており、cdが実行されていない。

調べてみると、以下のような話。

Issue executing a command within a directory · Issue #719 · capistrano/capistrano

よく見るとドキュメントにも書いてあった。
というわけで、以下のように書きなおしてみた。

namespace :deploy do
  task :link_html => [:set_rails_env] do
    on roles(:web) do |host|
      within "#{release_path}/public" do
        execute :ln, '-nfs', '/opt/htdocs/hoge'
        execute :ln, '-nfs', '/opt/htdocs/foo'
        execute :ln, '-nfs', '/opt/htdocs/bar'
      end
    end
  end
end

問題なく実行された。
よかったよかった。

9
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
4