Sunday 21 February 2016

ssh agent and forwarding on Arch Linux for Ansible

I have been using Ansible a lot for automation of deployments recently. One of my deployments had the need to clone a git hosted project from a server in the cloud. I did not want to have to place my private key on the cloud server for security reasons. The answer for me was setting up an ssh agent on my Arch Linux workstation to simplify working for ssh keys. With the ssh agent in place I could use ssh agent forwarding to authenticate using the private key on my workstation. The same process would work for any version of Linux.

SSH Agent set-up

On the Arch Linux Wiki there is a number of suggestions but the one I found was the easiest was from this StackOverflow article by adding the following to my ~/.bash_profile
SSH_ENV="$HOME/.ssh/environment"

function start_agent {
echo "Initialising new SSH agent..."
/usr/bin/ssh-agent | sed 's/^echo/#echo/' > "${SSH_ENV}"
echo succeeded
chmod 600 "${SSH_ENV}"
. "${SSH_ENV}" > /dev/null
/usr/bin/ssh-add;
}

# Source SSH settings, if applicable

if [ -f "${SSH_ENV}" ]; then
. "${SSH_ENV}" > /dev/null
ps -ef | grep ${SSH_AGENT_PID} | grep ssh-agent$ > /dev/null || {
    start_agent;
}
else
start_agent;
fi
This will check if you already have an ssh-agent running and if not will start a new agent. You can always check its running:
$ pgrep -a ssh-agent
23409 /usr/bin/ssh-agent
The ssh-agent daemon will automatically import the private key ~/.ssh/id_rsa which can be listed with:
$ ssh-add -L
Other private keys can be included for use by the ssh-agent with :
$ ssh-add <path to private key>

Agent Forwarding

Within my /etc/ansible/ansible.cfg file I set the following ssh settings
[ssh_connection]
ssh_args = -o ControlMaster=auto -o ControlPersist=60s -o ForwardAgent=yes
When Ansible is on the remote machine and clones from the git project the authentication will automatically be forwarded to my Arch workstation to be authenticated by the ssh-agent.

No comments:

Post a Comment