As you create more playbooks, you may find that you can utilize code from playbooks you have earlier created. For example , a playbook designed to set up a Nginx webserver one application could be adapted to configure a Nginx server for a different application, simply by changing the domain name , and path , and ownership. Here we will discuss about use roles by ansible galaxy.
Ansible roles are an excellent method for managing your playbooks and enhancing their re-usability. Roles organised the directory structure like tasks, variables, and files , handlers that are specifically designed to carry out a particular task. You can copy that role directory structure from one project to another proejct simply by copying that directory and call that roles from main play to execute it.
Using roles can help you to:
- Manage your playbooks : Roles organised playbooks according to related tasks together.This makes your playbooks easier to read and understand.
- Reusable your playbook : Roles can be reused in different playbooks. This save a lot of time and efforts .
- Improve the readability and maintainability of playbooks: Roles can help to improve the readability and maintainability the playbooks by differentiate the concept of your playbooks from the configuration data. This makes your playbooks easier to understand and modify.
- Roles can be design in parallel by different developers .
Create a Role Structure using Ansible Galaxy :
To create a role, you need to create a directory structure that follows the Ansible role directory layout . The ansible-galaxy command utility is used to create role structure and manage ansible roles .
ansible-galaxy init with role name argument will create the directory structure for new role on the current path.
# ansible-galaxy init role_name
defaults handlers meta README.md tasks tests vars
In the defaults/default.yml file contains the default values for the variables that are used in the role.The handlers/ directory contains the handlers that are executed when certain events occur. The tasks/ directory contains the tasks that are executed by the role. The meta/main.yml file contains the metadata for the role, such as the name of the role, the author of the role, and the description of the role.
Use Roles in Your Playbooks:
To use a role in your playbook, you have to call the roles to your playbook. The roles: section define the roles that are used by the playbook. For example, the following playbook uses the role_name :
- name: Test for user role
The roles parameter will import role in your project .
Best Practices for Using Roles
Here are some best rules to define the roles .
- Define the clear and descriptive names for your role . This will make easy to find and use your roles.
- Use consistent naming conventions for your directories and files .
- Dry run or test run your roles before you use them in live production system.