Site icon UnixArena

Ansible – What is Roles ? Playbook vs Role

Playbook is often used to complete simple tasks. When you would like to perform the multiple tasks, restarting services and copying files for a single job, you must consider using “roles” instead of writing the lengthy playbooks. Roles uses the known file structure to keep the various elements in different directories. For an example, handlers(restarting service) will be kept in handlers directory. Roles often simplify the code since it’s breaking into small pieces.

 

Here are the few Rules to use Role: 

 

Role Structure : 

Ansible – Roles – Structure

Creating a New Role: 

1. Identify the default role path for the ansible environment from a configuration file.

[linadm@ansible-server roles]$ grep roles ansible.cfg
roles_path    = /home/linadm/automation/roles:/usr/share/ansible/roles
[linadm@ansible-server roles]$

 

2. Navigate to the roles directory and create the new role to install VMware Tools on RHEL Linux VM.

[linadm@ansible-server roles]$ ansible-galaxy init Install_VMware_tools_RHEL
- Install_VMware_tools_RHEL was created successfully
[linadm@ansible-server roles]$ ls -ld Install_VMware_tools_RHEL
drwxrwxr-x 2 linadm linadm 6 Aug  3 17:14 Install_VMware_tools_RHEL
[linadm@ansible-server roles]$

 

3. Create the directory for the new role. Navigate to the newly created role directory.

[linadm@ansible-server Install_VMware_tools_RHEL]$ ls -lrt
total 4
-rw-r--r-- 1 root root 1328 Aug  9 18:54 README.md
drwxr-xr-x 2 root root    6 Aug  9 18:54 templates
drwxr-xr-x 2 root root    6 Aug  9 18:54 files
drwxr-xr-x 2 root root   22 Aug  9 18:54 defaults
drwxr-xr-x 2 root root   22 Aug  9 18:54 handlers
drwxr-xr-x 2 root root   22 Aug  9 18:54 meta
drwxr-xr-x 2 root root   22 Aug  9 18:54 tasks
drwxr-xr-x 2 root root   39 Aug  9 18:54 tests
drwxr-xr-x 2 root root   22 Aug  9 18:54 vars
[linadm@ansible-server Install_VMware_tools_RHEL]$

Note: This article intention is to just explain the functionality of the ansible role.

 

4. Here, I have already created the required files under each directory.

[linadm@ansible-server Install_VMware_tools_RHEL]$ tree
.
├── default
│   └── main.yml
├── files
│   ├── kmod-vmware-tools-vmxnet3-1.4.rpm
│   ├── kmod-vmware-tools-vsock-9.8.1.rpm
│   └── vmware-tools-core-10.3.2-1.el5.rpm
├── handlers
│   └── restart_vmware_tools.yml
├── tasks
│   └── RedHat.yml
└── tests
    └── Redhat.yml

5 directories, 7 files
[linadm@ansible-server Install_VMware_tools_RHEL]$

 

Conclusion

In Playbook, you will be combining all the elements into a single file. But roles split the code in the respective directory and simplifies the code.

 

Exit mobile version