LoginSignup
1
0

More than 1 year has passed since last update.

【ざっくり解説】Capistranoでsudoを使いたい

Posted at

問題点

Capistranoを使ってRailsアプリケーションをデプロイしていたところ、
カスタムで作成したApache再起動タスクでエラーが起きた。

** Execute deploy:restart
  01 sudo systemctl restart apache2
  01 sudo
  01 :
  01 a terminal is required to read the password; either use the -S option to read from standard input or configur...
  01 
cap aborted!

おぉん…。

調べた結果、ptyをtrueにする必要があるとのことで、それを試してみる。

deploy.rb
# Default value for :pty is false
set :pty, true

再度、自動デプロイを実行。

** Execute deploy:restart
00:00 deploy:restart
   01 sudo systemctl restart apache2
   01 [sudo]password for username:
passw.. # パスワードが丸見え…

おぉん…パスワード丸見えやね。
しかも正しいパスワードを入れてEnterを押下してもその後反応なし。

解決法

sshkit-sudoというGemのお力を借りしました。

とりあえずGemfileを記述して、bundle installも忘れずに。

Gemfile
gem 'sshkit-sudo'

Capfileにsshkit/sudoを追加。

Capfile
require 'sshkit/sudo'

そして従来はexecute :sudoとしていたところを、以下のようにexecute! :sudoとします。

deploy.rb
- execute :sudo, 'systemctl restart apache2'
+ execute! :sudo, 'systemctl restart apache2'

ついでにptyはいらないっぽいので、再度コメントアウトしておきます。

deploy.rb
# Default value for :pty is false
# set :pty, true

ここまで設定したら、Capistranoで自動デプロイを実行します。

** Execute deploy:restart
00:00 deploy:restart
   01 sudo systemctl restart apache2
   01 [sudo]password for username:
# パスワードを入力...
 ✔︎  01 username@host 0.030s
** Invoke...

対話的にパスワードを入力し、無事にapache再起動タスクが完了しました。

余談

前回の記事でご紹介しましたが、Capistranoは非対話型・非ログインシェルを割り当てています。

公式のREADMEにも、「sudoを使わない方がスムーズに自動デプロイできるよ」という趣旨の記述があり、やんわりとsudoの使用が非推奨になっています。

今回はGemの力をお借りして実装しましたが、できればsudoを使わない方が公式に則った安全策と言えそうです。sudoを使わない、あるいは使ったとしても対話しないような方法についても、今後調査してみたいと思います。

参考にしたドキュメント・記事

1
0
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
1
0