Ansible is one of the most powerful automation tools that helps streamline IT tasks, such as configuration management, application deployment, and orchestration. As the IT environment grows in complexity, managing Ansible playbooks can be challenging. This is where Ansible roles come into play, bringing clarity and ease in debugging.
So, what are Ansible roles?
Ansible roles provide a structured and modular way to organize automation tasks. Roles break down the playbooks into small reusable components and focus on one functionality at a time. By using a standardized directory structure, roles can improve maintainability, promote collaboration, and enable easy automation workflows.
They also maintain consistency, leading to reduced errors and improved efficiency. Instead of repeatedly writing the same tasks again and again, you can reuse the same Ansible roles.
In this guide, we shall understand how Ansible roles can help with automation.
Understanding Playbooks with Roles
Ansible Playbooks define automation tasks but they lack proper structuring. This is why Ansible roles help organize playbooks by dividing them into smaller reusable components for each function. By structuring tasks, variables, templates, and files within a role, Ansible ensures better execution and reusability.
Get exclusive access to all things tech-savvy, and be the first to receive
the latest updates directly in your inbox.
Structure of an Ansible Role
A typical Ansible Role follows a predefined directory structure:
rolename/
|– defaults/ # Default variables
|– files/ # Static files to be copied
|– handlers/ # Handlers for notifications
|– meta/ # Role metadata
|– tasks/ # List of tasks to execute
|– templates/ # Jinja2 templates
|– vars/ # Variable definitions

This uniform approach makes sure that playbooks are easy to maintain and read.
Related Article: A beginners Guide To Install Ansible on Ubuntu
Creating and Using Ansible Roles
To create an Ansible Role, use the following command:
ansible-galaxy init my_role
This command generates the standard directory structure for the role.
To use a role in a playbook, reference it as follows:
– hosts: webservers
roles:
– my_role
Additionally, roles can be applied dynamically using the include_role or import_role directives in tasks:
– name: Include my_role dynamically
include_role:
name: my_role
This allows extreme flexibility, mainly when Ansible roles need to be executed with condition parameters.
Defining Tasks Within a Role:
Within the tasks/ directory, a main.yml file typically contains the set of tasks to execute. An example might look like this:
– name: Install Nginx
apt:
name: nginx
state: present
– name: Start Nginx service
service:
name: nginx
state: started
enabled: yes
By structuring tasks in Ansible roles, you make automation workflows much more easy, modular, and reusable.
Best Practices for Ansible Roles
Following some best practices can help you leverage Ansible roles to the maximum:
- Follow a standard and uniform structure to keep tasks, variables, and templates in the designated directories for better organization.
- Define configurable parameters in defaults/main.yml instead of hardcoding values.
- Keep roles reusable by designing Ansible roles to be adaptable across multiple environments by avoiding environment-specific configurations.
- Document the role by maintaining a README.md file to describe the role’s purpose, usage, and required variables.
- Define dependencies in meta/main.yml to ensure that required roles are executed in the correct order.
- Use the right and useful tools like ansible-lint to check for syntax errors and best practices before applying a role in production.
- Avoid hardcoded values and use variables and templates to increase flexibility and scalability.
- Keep the roles focused on one task at a time.
Sharing and Reusing Ansible Roles
Ansible roles can be shared and reused to standardize automation across different projects to maintain consistency.
- Using Ansible Galaxy
The Ansible Galaxy is a public repository for all users where users can find pre-built Ansible roles.
- Install a role from Ansible Galaxy:
ansible-galaxy install my_role
- List installed roles:
ansible-galaxy list
- Create a role structure using Galaxy:
ansible-galaxy init my_role
- Publish a role to Ansible Galaxy:
ansible-galaxy role publish my_role
- Use a Galaxy role in a playbook:
– hosts: webservers
roles:
– geerlingguy.nginx # Example of a role from Ansible Galaxy
- Using a Private Git Repository
- Clone and use a role from Git:
ansible-galaxy install -p roles -r https://github.com/myorg/my_ansible_role.git
- Reference the role in the playbook:
– hosts: all
roles:
– role: my_ansible_role
vars:
some_variable: value
- Reusing Roles with Requirements Files
A requirements.yml file helps manage multiple roles efficiently.
- Example requirements.yml file:
– src: geerlingguy.nginx
version: 3.1.0
– src: https://github.com/myorg/my_ansible_role.git
name: my_custom_role
- Install roles from requirements.yml:
ansible-galaxy install -r requirements.yml
- Role Dependencies
Roles can have dependencies on other roles, defined in meta/main.yml:
dependencies:
– role: common
– role: security
vars:
firewall_enabled: true
This ensures the dependent roles execute in the correct order.
Troubleshooting Guide For Ansible Roles
Issue | Possible Causes | Solutions |
Role Not Found | – Role is not located in the roles_pathdirectory.- The role has not been installed via ansible-galaxy. | – Check the roles_path in ansible.cfg.- Install the required role using ansible-galaxy install <role_name>. |
Variable Conflicts | – Same variable names used across different roles.- Variable precedence issues. | – Use namespaced variables (e.g., my_role_var).- Define role-specific variables inside vars/ and defaults/ to control precedence. |
Permission Issues | – Users running Ansible lack necessary privileges.- Incorrect file permissions on copied files. | – Use become: yes for privilege escalation.- Ensure correct file ownership using the file module. |
Missing Dependencies | – Role dependencies are not defined in meta/main.yml.- Dependencies are not installed. | – Define dependencies in meta/main.yml.- Run ansible-galaxy install -r requirements.yml to install missing dependencies. |
Handlers Not Triggering | – Task doesn’t notify the handler.- Handler name mismatch. | – Ensure notify directive is present in the task.- Verify that the handler name matches exactly. |
Task Execution Order Issues | – Dependencies between tasks not handled properly.- Conditional execution misconfigured. | – Use depends_on in meta/main.yml for role dependencies.- Use when conditions to control execution properly. |
File or Template Not Found | – Incorrect path specified.- File is missing in the files/ or templates/directory. | – Use the debug module to check paths.- Ensure the file exists in the correct role directory. |
Playbook Fails on a Specific Host | – Host-specific issue (e.g., missing dependencies).- Role not applicable to that host. | – Use ansible -m ping all to check connectivity.- Implement conditional execution (when statements) to handle different environments. |
YAML Syntax Errors | – Incorrect indentation.- Missing colons or quotes. | – Validate YAML files using ansible-lint or yamllint.- Ensure correct indentation and syntax. |
Slow Role Execution | – Inefficient task execution.- Large loops without optimization. | – Use async and poll for background execution.- Optimize loops with with_items or loop to reduce execution time. |
Wrapping Up – Ansible Roles
Ansible roles are small but mighty elements of a Playbook, they help maintain a structured approach to automation. Leveraging Ansible roles with playbooks using this guide will help you reduce overhead and increase efficiency.
Frequently Asked Questions
1. Where are Ansible Roles stored?
Roles are typically stored in the /etc/ansible/roles/
directory or in a custom path defined in ansible.cfg
.
2. How do I troubleshoot Ansible Roles?
Common troubleshooting steps include:
– Checking the roles_path
in ansible.cfg
.
– Using ansible-lint
to validate syntax.
3. How can I share Ansible Roles?
You can share roles using Ansible Galaxy or store them in a private Git repository for team collaboration.