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:
- Group the tasks in a single role.
- Each role has a single responsibility.
- The role requires the directory structure.
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]$ mkdir Install_VMware_tools_RHEL [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 0 drwxrwxr-x 2 linadm linadm 6 Aug 3 17:18 tests drwxrwxr-x 2 linadm linadm 6 Aug 3 17:18 tasks drwxrwxr-x 2 linadm linadm 6 Aug 3 17:18 handlers drwxrwxr-x 2 linadm linadm 6 Aug 3 17:18 default [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]$
- All the required files will go in the “files” directory
- All the tasks will go in to “tasks“
- Post restart tasks will go into “handlers” directory
- The “default” directory’s main.yml will consist of the pre-validation and calling the tasks.
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.
The post Ansible – What is Roles ? Playbook vs Role appeared first on UnixArena.