One of the first things I wanted to do when I started using Ansible was to clone a git repository on a remote machine as I keep configuration, scripts, and source code in github or gitlab repositories. Things that are not meant for the public, I store in private repositories that I want to clone via ssh. Cloning and updating them I now want to automate with Ansible.
There are different ways to go for this task:
- Checkout the repo locally and copy it to the server via a Ansible synchronize task
- Generate an ssh key on the server and allow cloning the repo with that key manually
- Copy a local ssh key to the server and allow cloning the repo with that key
- use ssh-agent to load the local key and forward the agent to the server
Now we need to enable the forwarding of the ssh agent to the remote machine so we can access the loaded key remotely. There are different ways to do so, but I find it most useful to do it in your ansible.cfg like this:
That way, you allow the forwarding for all your Ansible-managed hosts at once.
Now you can go on executing your playbook and should be able to clone the repository on the remote host.
To make it even easier, we can add a task to load the ssh-key before executing the other tasks in the playbook. For this, add the local host to your Ansible inventory:
Now we can add a small shell task to load the ssh-key:
When you now execute the playbook, you shouldn’t need to load the ssh-key before.Tags: ansible, bash, coding, devops, opensource, scripting, software development
Categorised in: Uncategorized
This post was written by Manuel Dewald