Writing an Ansible Role for Galaxy

Photo credit: Unsplash: grakozy

I’ve mentioned a few times how I’ve moved to use Ansible more and more for server provisioning and change management.

One thing that I recently embarked on was making an Ansible version of the Chef Cookbook that I use most often. The recipe is used to help me install the correct public keys into the authorized keys file for SSH access to servers I maintain. It uses GitHub Organizations and Users to fetch the public keys that GitHub users have added to their profiles. It also supports adding specific hardcoded keys, useful for deployment scripts or other types of programatic access.

You can view the Ansible Role that I created on Galaxy and the source.

Writing the Role

Vagrant is your friend. I’ve used Vagrant for a number of different development tasks, but it really worked great for developing an Ansible role. It is always important to test your development, and Vagrant made it really easy to start fresh and test again and again.

Get started by reading the documentation from Ansible, it is a great guide. Pay particular attention to the good practices:

Ansible gives some really great building blocks, so I didn’t need to write any custom code, just leverage the built in modules. All in all, I used these modules:

Compared to Chef

Compared to Chef, it was a little harder to write since I couldn’t just mix in Ruby code to accomplish what I wanted, but stuck to the building blocks of Ansible. I think that in the end, this will make it more maintainable and more resistant to version changes of Ansible, which is one of my largest issues with Chef.

The tight integration of GitHub and Ansible’s Galaxy is awesome, making it easy to publish and keep things up-to-date.

I was able to pretty easily test Chef recipes with Vagrant or Docker. Testing with Ansible on Travis-CI is pretty easy, and I was able to also leverage Docker for testing using this great guide from Jeff Geerling.

Overall it was a great experience, and I’d look forward to doing it again if the need arises. There is also room for improvement in the current role. Right now, you can only use it to install keys into a single user account, unless you include the role more than once with different variables each time. It would be nice to give variables for configuration that allow the role to be included just once as setup all the user accounts necessary.