Improving your playbooks with roles
Within an enterprise, when configuring a VM, we notice a certain repetition of tasks for each application, for example, several applications require the identical installation of nginx, which must be performed in the same way.
With Ansible, this repetition will require duplicating the playbook code, seen in our playbook example in the Writing a basic playbook section, between several playbooks (because each application contains its playbook). To avoid this duplication and, hence, save time, avoid errors, and homogenize installation and configuration actions, we can encapsulate the playbook code in a directory called role that can be used by several playbooks.
To create the nginx role corresponding to our example, we will create the following directory and file tree within our devopsansible directory:
Then, in the main.yml file, which is located in tasks, we will copy and paste the following code from our playbook in the file that is created:
- name: install and check nginx latest version
apt: name=nginx state=latest
- name: start nginx
service:
name: nginx
state: started
Then, we will modify our playbook to use this role with the following content:
---
- hosts: webserver
roles:
- nginx
Following the node roles, we provide a list of roles (names of the role directories) to be used. So, this nginx role is now centralized and can be used in several playbooks simply without having to rewrite its code.
The following is the code of a playbook that configures a VM web server with Apache and another VM that contains a MySQL database:
---
- hosts: webserver
roles:
- php
- apache
- hosts: database
roles:
- mysql
However, before we start creating a role, we can use Ansible Galaxy (https://galaxy.ansible.com/), which contains a large number of roles provided by the community and covers a high number of configuration and administration needs.
Within an enterprise, we can also create custom roles and publish them in a private galaxy within the company. More information can be found here: https://docs.ansible.com/ansible/latest/dev_guide/developing_modules_general.html.
In this section, we have detailed the writing of a playbook as well as its improvement with the use of roles. All of our artifacts are finally ready, so we will now be able to execute Ansible.