capistranoをほんのちょっと動かしてみる⑤(ssh鍵接続設定)
sshの鍵を作成して鍵を転送してみる。 ※のちのちパスワード認証から鍵認証に変更するためのテストも兼ねて
事前作業
鍵をrsaで作成
$ ssh-keygen -t rsa
Generating public/private rsa key pair.
Enter file in which to save the key (/root/.ssh/id_rsa):
/root/.ssh/id_rsa already exists.
Overwrite (y/n)? y
Enter passphrase (empty for no passphrase):
Enter same passphrase again:
Your identification has been saved in /root/.ssh/id_rsa.
Your public key has been saved in /root/.ssh/id_rsa.pub.
The key fingerprint is:
5e:2c:65:f3:30:42:da:f5:86:38:ae:2e:9e:76:2f:b5 root@capistrano.localdomain
The key's randomart image is:
+--[ RSA 2048]----+
+-----------------+
鍵を適当な場所にコピー
$ mkdir -p /opt/capistrano/manage/files/root/.ssh
$ cat /root/.ssh/id_rsa.pub > /opt/capistrano/manage/files/root/.ssh/authorized_keys
$ ls -l /opt/capistrano/manage/files/root/.ssh/authorized_keys
-rw-r--r--. 1 root root 409 Jul 7 05:58 /opt/capistrano/manage/files/root/.ssh/authorized_keys
新規するファイルは下記。 ./config/develop/ssh.rb
# ./config/deploy/manage.rbと同様に./config/servers.rbを読み込む
load './config/servers.rb'
task :up_key do
# アップロードディレクトリ等を設定
src = '/opt/capistrano/manage/files/root/.ssh/authorized_keys'
dir = '/root/.ssh'
dst = '/root/.ssh/test_keys'
on roles( :client ) do
# ディレクトリが存在しなかった場合、作成
execute "test -d #{dir} && mkdir -p #{dir}"
# アップロード(recursiveは再帰的に処理をするためだが今回は無くてもOK)
upload! src, dst, :recursive => true
# 一時ファイルからauthorized_keysに追記
execute "cat #{dst} >> #{dir}/authorized_keys"
#一時ファイルの削除
execute "rm -f #{dst}"
end
end
end
とりあえず1台だけ(openvz)実行したいので下記を修正。 ※これ以外は(4)のファイルそのまま ./config/servers.rb
SSHKit::Backend::Netssh.configure do |ssh|
ssh.ssh_options = {
:user => 'root',
# :passphrase => 'passphrase',
:password => 'test',
}
end
role :client, %w{openvz}
実行してみる。
$ cap ssh exec:up_key
INFO [4990c760] Running /usr/bin/env test -d /root/.ssh && mkdir -p /root/.ssh on openvz
DEBUG [4990c760] Command: test -d /root/.ssh && mkdir -p /root/.ssh
INFO [4990c760] Finished in 0.135 seconds with exit status 0 (successful).
DEBUG Uploading /opt/capistrano/manage/files/root/.ssh/authorized_keys 0.0%
INFO Uploading /opt/capistrano/manage/files/root/.ssh/authorized_keys 100.0%
INFO [745f0512] Running /usr/bin/env cat /root/.ssh/test_keys >> /root/.ssh/authorized_keys on openvz
DEBUG [745f0512] Command: cat /root/.ssh/test_keys >> /root/.ssh/authorized_keys
INFO [745f0512] Finished in 0.019 seconds with exit status 0 (successful).
INFO [f8328a0c] Running /usr/bin/env rm -f /root/.ssh/test_keys on openvz
DEBUG [f8328a0c] Command: rm -f /root/.ssh/test_keys
INFO [f8328a0c] Finished in 0.019 seconds with exit status 0 (successful).
できたっぽいのでsshで接続する。
$ ssh root@openvz
Enter passphrase for key '/root/.ssh/id_rsa':
Last login: Tue Jul 7 07:56:34 2015 from 172.31.13.92
$ hostname
openvz
パスワードではなくパスフレーズになったので出来た気がする。