LoginSignup
6
6

More than 5 years have passed since last update.

Ansibleでssh-agentが働いてない時は

Last updated at Posted at 2017-10-18

※CentOS 7.x → CentOS 7.x のsshを想定しています。

SSHエージェント転送を有効にして、手元の秘密鍵をログイン先でも使いたい場合がある。

具体的にはWebアプリケーションの展開先のサーバにsshでつないで、githubやvisualsutio.comのようなprivateなgitリポジトリからソースコードをcloneしたい時など。

もっというと、僕の場合はこれをAnsibleのplaybookで実行してアプリケーションをデプロイしたいとき。

今回その秘密鍵の転送がうまくいかなかったので、確認方法と解決策を記載する。

確認方法:

$ ssh-add -l

上記コマンドで、手元の秘密鍵のリストが表示できるか。
sshエージェントが働かない時は、上記のコマンドを打っても以下の様なエラーになる。

$ ssh-add -l
Could not open a connection to your authentication agent.

この状態の場合、以下のコマンドでエージェントを起動する。参考

$ ssh-add -l
Could not open a connection to your authentication agent.
$ eval "$(ssh-agent)"
Agent pid 52616

その状態でssh-addで秘密鍵をエージェントに追加し、

$ ssh-add -l
Could not open a connection to your authentication agent.
$ eval "$(ssh-agent)"
Agent pid 52616
$ ssh-add
Identity added: /home/***/.ssh/id_rsa (/home/***/.ssh/id_rsa)
$ ssh-add -l
2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx /home/***/.ssh/id_rsa (RSA)

-A オプションをつけてsshすると接続先でも利用できるようになる。

$ ssh-add -l
Could not open a connection to your authentication agent.
$ eval "$(ssh-agent)"
Agent pid 52616
$ ssh-add
Identity added: /home/***/.ssh/id_rsa (/home/***/.ssh/id_rsa)
$ ssh-add -l
2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx /home/***/.ssh/id_rsa (RSA)
$ ssh -A user@yyy.yyy.yyy.yyy
Last login: Wed Oct 18 07:51:13 2017 from xxx.xxx.xxx.xxx
[user@server~]$ ssh-add -l
2048 fb:53:c1:75:1b:4d:53:d0:54:c0:1f:43:10:a5:51:c0 /home/***/.ssh/id_rsa (RSA) # 同じ秘密鍵を参照できた

※sshにログインするたびに上記コマンドが必要なので、~/.bashrcに書いておくとよさそう。

Ansibleでプライベートリポジトリからcloneするplaybookを実行するときは、まず、カレントディレクトリに以下のファイルを保存する。

ansible.cfg
[ssh_connection]
ssh_args = -o ForwardAgent=yes

その後、Ansibleの実行前にSSHエージェントを起動して実行する。

$ eval "$(ssh-agent)"
Agent pid 52616
$ ansible-playbook -i hosts play.yml # (gitをインストールしてcloneするplaybook)

これでも動かない時は、本記事の範囲外だがgit cloneのtaskでbecome:noになってるか、リポジトリがAnsibleホストのknown_hostsに登録されているかどうかも要確認。

参考文献:
ssh-addに失敗する場合の対処:Could not open a connection to your authentication agent.:Technical tips:Media hub
http://tech.clickyourstyle.com/articles/105
Connect to your Git repos with SSH | Microsoft Docs
https://docs.microsoft.com/ja-jp/vsts/git/use-ssh-keys-to-authenticate
Ansible で git clone させる by @seizans on @Qiita https://qiita.com/seizans/items/f5f052aec1592c47767f

6
6
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
6
6