I've been using SSH agent forwarding with Ansible for the last few projects I've been working on and I thought I'd just share my setup here.
The neat thing with SSH agent forwarding is not having to store your SSH keys on your servers when pulling down your Git repo during deployment.
For example, I can deploy new code to my servers through Ansible from my local machine using my local SSH keys. The servers I'm connected to are basically using the ssh-agent running on my machine as if it's running on those servers.
I also like to use Jenkins for deployment and there's an SSH Agent plugin for it. So what I normally do is create a deployment key on Bitbucket or GitHub and give that read-only access to the repo. Then in Jenkins, all my jobs are configured to use SSH Agent and I specify that key.
This way, if I'm managing 100 servers and I need to change the SSH keys, I can simply just change that in one place in Jenkins instead of having to run a command to update the SSH keys on the servers.
Here are the steps to get SSH Agent forwarding to work with an Ansible project.
Create an ansible.cfg file with the following content
host_key_checking = False
ssh_args = -o ForwardAgent=yes -o ControlMaster=auto -o ControlPersist=60s
Run ssh-agent and add your keys
>>> ssh-agent bash
>>> ssh-add ~/.ssh/mykey_id_rsa
If SSH agent forwarding doesn't seem to be working, you can try the following:
- Make sure there are keys loaded in ssh-agent by typing in the ssh-add -L command.
- If you rebuilt the server, the known_hosts verification might be failing. You can try ssh-ing directly to the server and see if you get a warning and follow the instructions. You can also just delete/backup the ~/.ssh/known_hosts file.
- Try opening a new console and run the ssh-agent and add the keys again.