結論から言うと以下の流れで解決。
1)ssh-agentの設定
2)ansible.cfgの設定
3)ansible taskの設定
1) ssh-agentの設定
以下のサイトにまとまっているので、そのとおりに対応。
qiita.com
この設定を行うことで、ssh接続時のパスフレーズ入力を省略することができる。
ただし「ssh-agent」を使用すると、パスフレーズの入力を省略できるため非常に便利だが、その分セキュリティレベルは当然低下する。
作業端末から離れる場合は「ssh-agent」を停止させたり、重要なサーバ(本番サーバ等)への接続には使用しないなどのルールが推奨される。
[参考]
laboradian.com
https://32imuf.com/ssh/command/ssh-add/
https://qiita.com/naoki_mochizuki/items/93ee2643a4c6ab0a20f5
2)ansible.cfgの設定
以下をansible.cfgに追記する
[ssh_connection] ssh_args = -o ForwardAgent=yes
[ssh_connection]ヘッダの下で、ssh_argsを設定することで、特定のsshオプションを設定できる。大体は以下のように渡すオブション毎に、「-o」を設定する
例
[ssh_connection] ssh_args = -o ControlMaster=auto -o ControlPersist=60s
上記の設定では、ssh-agentのForwardAgent(エージェント転送機能)をonにしている。
3)ansible taskの設定
- name: Git clone project git: repo: "{{ project_git_repo }}" dest: "{{ working_direcory }}" version: master accept_hostkey: yes become_flags: '-E' tags: git
すごく大事なのは「become_flags: '-E'」
'-E'オプションの意味は「現在の環境変数を保持してコマンドを実行する」という意味になる。
【 sudo 】コマンド――スーパーユーザー(rootユーザー)の権限でコマンドを実行する:Linux基本コマンドTips(68) - @IT
Githubからcloneするため、SSHエージェント転送機能を使用する時に、サーバに環境変数として保存される「SSH_AUTH_SOCK」を
使用する必要があるためと見られる。
The agent outputs environment variable settings that this puts in place. The SSH_AUTH_SOCK environment variable is set to point to a unix-domain socket used for communicating with the agent
ssh-agent - How to configure, forwarding, protocol.
This fails if you do
> sudo git clone git@github.com:my-github-account/my-repo.git
because your environment variables are not available to the
commands running under sudo.However, you can set the SSH_AUTH_SOCK variable for the command by
passing it on the command line like so> sudo SSH_AUTH_SOCK=$SSH_AUTH_SOCK git clone git@github.com:my-github-account/my-repo.git
and all is well.
Git clone using ssh agent forwarding and sudo · GitHub
※1 ancible.cfg内の[privilege_escalation]ヘッダ内で以下の設定を入れても良い。
[privilege_escalation] become_flags = -E
※2 昔の記事を探すと「sudo_flags = -E」を設定する記事も出てくるが
これは新しいバージョンでは廃止になるものなので、上記でやったほうが良い。
[参考]
Deprecation warning when using "sudo_flags" in ansible.cfg · Issue #47006 · ansible/ansible · GitHub
How do I use remote machine's SSH keys in ansible git module - Stack Overflow
Ansible and Git Permission denied (publickey) at Git Clone - Stack Overflow
Configuration file — Ansible Documentation
Understanding privilege escalation: become — Ansible Documentation