Short definition of a role
An Ansible role is a set of reusable tasks that you can use into multiple playbooks and even share with the community using Ansible Galaxy
When should you refactor your playbooks into roles ?
- You mix different concerns about your app in a single playbook
- Your playbook is getting too complex
- You have to write a new playbook for an use case similar to an existing playbook
- Some logic of your playbook can be replaced by community maintained roles (Docker Swarm setup for instance)
Real world example
Deploy two web applications with playbooks
Imagine you have to deploy two web applications connected to the same database. Here is the example deployment scheme you have:
- Install and configure the database, add a database user for each web app
- Install Nginx with ACME challenge support
- Use let’s encrypt to get a SSL certificate for each web app domains
- Deploy both web applications
You would want to write two playbooks, one for each web application deployment. If you don’t use roles, you would have to copy/paste the database setup logic to both of the playbooks. In order to setup trusted and free SSL certificate, you would have to write few blocks of scripts with shell calls to LetsEncrypt certbot, handle certificate renewal, etc.
How Ansible roles can improve this deployment process
We could write two roles:
- A database role responsible of the database setup and database users management
- A Nginx role which handle core configuration (such as ACME challenge support) and manage available sites templates
We will use also an Ansible community role for configuring Let’s encrypt and obtaining the certificates. This will save us a lot of time and efforts implementing LetsEncrypt logic, and benefit from the expertise of the community that wrote the playbook. Usually the source code of an Ansible role is short and well written, so don’t hesitate to take a look at the source code available on Github
Here is the new playbooks we have for each web application:
- Configure the roles variables such as database user, nginx site template name, etc
- Import project database role
- Import project Nginx role
- Import community role for let’s encrypt
- Run specific logic for this web application deployment
The deployment process have been improved using roles: you wrote once how to install the database and Nginx proxy, as well as adding users to the database and sites to the proxy. Ansible Galaxy brought great quality code to your project so you just have to configure LetsEncrypt role variables to get your free SSL certificates