Introduction to roles
Here the Video Transcript
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: Disable and stop chronyd daemon
service:
name: chronyd
enabled: no
state: stopped
ignore_errors: true
- name: Install ntpd daemon
yum:
name: ntp
state: latest
- name: Allow IPMI and node network to query ntp server
blockinfile:
dest: /etc/ntp.conf
insertafter: '^#restrict '
block: |
restrict 192.168.0.0 mask 255.255.240.0 nomodify notrap
restrict 192.168.16.0 mask 255.255.240.0 nomodify notrap
- name: Enable and Restart ntpd daemon
service:
name: ntpd
enabled: yes
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.