Ansible- ROLES
--
The best way to manage code is creating Roles in Ansible. Role is just a directory or an folder.
With Role, we create sperate file for vars, tasks, handlers and other Ansible artifacts. Organizing the files this way helps in managing the project/code better. Also, for any changes required in specific file we can just focus on that file and make necessary changes.
To organize the files, Ansible follows standard format or template. Ansible provide tool call Galaxy to create this standard format.
Ansible-Galaxy knows how to create and manage the files. Let’s get into practice.
usage: ansible-galaxy [-h] [--version] [-v] TYPE ...
Create project workspace. Sample like below.
# Create working area
$ mkdir myansiblework# Get into Working area.
$cd myansiblework# Check for existing Role.
$ ansible-galaxy role list# Create a ansible Role.
$ ansible-galaxy role init <<RoleName>>
# To run the full project's Role we can create a Playbook which will invoke all the role's files for setup.
By default Ansible looks for Roles in below path:
- /usr/share/ansible/roles
- /etc/ansible/roles
If you want to use separate directory path , need to update the configuration file. go-to — /etc/ansible/ansible.cfg
Sample Role creation:
General skeleton of Role creation:
Directory Structure:
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.
vars — other variables for the role. Vars has the higher priority than defaults.
files — contains files required to transfer or deployed to the target machines via this role.
templates — contains templates which can be deployed via this role.
meta — may contain information about this role (author, dependency, examples, version etc.)
Using roles at the play level
The classic (original) way to use roles is with the roles
option for a given play:
---
- hosts: webserver
roles:
- common
- webservers
Sample Playbook that implements roles.
Role Directory:
Individual Roles directory: apache_webserver