Friday, 16 September 2016

Automation with Ansible

Ansible is a Python based automation tool. I started using it to revert changes made on my local machine every time there were package updates. That is I wanted to ensure my options and settings were preserved. Professionally my team uses Puppet but we were looking at alternatives. Ansible was chosen for a variety of reasons: it is easy to learn, has broad functionality and an active community. There is next to no new lingo to learn:
  • a task is an action you want to perform
  • a list of tasks can be organised into a playbook
  • handlers are special tasks that are triggered by a change in a task
  • a group of playbooks is organised into roles
  • an inventory is a list of hosts (or group of hosts) to apply a playbook to
  • playbooks are under the roles directory
  • tasks are stored in the tasks directory, under a role
  • variables are stored in the vars directory, under a role
  • templates are stored in templates directory, under a role
So, any typical Ansible project would look something like:

├── group_vars
│ └── all
├── host_vars
└── roles
  ├── menu
  │ ├── handlers
  │ └── tasks
  ├── vim
  │ ├── files
  │ ├── handlers
  │ ├── tasks
  │ └── vars
  └── x11

The example above is just a subset of roles from my project to manage my local machine.  You can see the full project on GitHub. There are now over 100 tasks being performed by this project. This grew incrementally, where each role could be developed independently from the others. Thats is, Ansible makes it easy for you to start small, and little by little, add functionality.

I recommend that you get to know the included core modules. If you find yourself invoking many command or shell tasks, then you probably need to re-read the list of modules or explore writing a custom module. Ansible works best when break a complex task into single action steps. Doing this has the added benefit of making it easy for you to test tasks as they are included. Re-running a role is natural as Ansible is idempotent. Of course, you can easily break this if invoking a shell script. Which is another reason to break down a complex operation into distinct tasks and use the provided modules.

Despite having written the original project to manage my home machine, this project (by virtue of hosts and groups) now manages other machines as well.

So, if you find yourself repeating tasks on multiple hosts, why not give Ansible a try?

See also my presentation (PDF) on Ansible Filters.

No comments: