Learning Ansible and codifying my infrastructure was one of the top goals for me this year. I don’t have everything codified yet, but I’m getting there. Aside from the obvious repeatability and consistency you get from using a tool like Ansible, I really like the fact that everything is automatic. Well, almost everything…

If you’re going to use passwordless SSH to connect Ansible to the host (which you should), you need to copy your pubilc key to the host box before running any playbooks. I ended up doing this several times after testing/blowing away/recreating the box, so I wrote a small script that handles it automatically.

#!/bin/bash
if [ $# -eq 0 ]
    then
        echo ""
        echo "Usage:"
        echo "inject-ssh.key.sh [path/to/key.pub] [user@ip.add.re.ss]"
        echo ""
        echo "Nothing is validated - be sure of what you're sending"
        echo ""
    else
        cat $1 | ssh $2 'mkdir ~/.ssh; cat >> .ssh/authorized_keys'
fi

Nothing special here, just copying the contents of the specified ssh key and writing it to the authorized_keys file on the host.