Introduction to roles
Roles are ways of automatically loading certain vars files, tasks, and handlers based on a known file structure. Grouping content by roles also allows easy sharing of roles with other users. A role can be used in a playbook by adding the tag roles which can be a list of roles:
---
# file: master.yml
- name: Provisioning for the master node
hosts: master
roles:
- ntp_server
...
Once a role is used, it is expected a folder called roles in the same path of the playbook. Inside of the roles directory, Ansible will lookup for a folder with the name of the role used (ntp_server) at execution time. This folder must contain at least one of the following directories:
tasks- contains the main list of tasks to be executed by the role.handlers- contains handlers, which may be used by this role or even anywhere outside this role.defaults- default variables for the role (see Working with variables for more information).vars- other variables for the role (see Working with variables for more information).files- contains files which can be deployed via this role.templates- contains templates which can be deployed via this role.meta- defines some metadata for this role. See below for more details.
When in use, each directory must contain a main.yml file containing the relevant content. Let us start with a minimal example:
root
├── master.yml
└── roles
└── ntp_server
└── tasks
└── main.yml
The file main.yml in the folder tasks must contain only the list of the tasks; i.e. without the hosts definition or the tasks tag. Extracting the tasks from the NTP server playbook, the main.yml file is:
---
# file: main.yml
- name: Install chrony
ansible.builtin.yum:
pkg:
- chrony
state: installed
- name: Enable local network devices to access the NTP service
blockinfile:
dest: /etc/chrony.conf
insertafter: '^#allow '
block: |
allow 192.168.0.0/20
allow 192.168.16.0/20
- name: Enable and Restart chronyd daemon
service:
name: chronyd
enabled: true
state: restarted
...
Note that the tasks in the main.yml are not tied to a specific host making the code reusable for any other host.