What are Ansible Roles?
An ansible role is group of tasks, files, and handlers stored in a standardized file structure. Roles are small functionalities which can be used independently used but only within playbook.
Simply put:
- Playbooks organize tasks,
- Roles organize playbooks.
Why Do We Need Ansible Roles?
When working with large-scale automation, using a single playbook for everything becomes messy. Roles address this challenge with structure and reusability.
Structure of an Ansible Role:
Structure of an ansible role consists of below given components:
- Defaults - Store default variables used within the role.
- Files - Store static files to be transferred to managed hosts.
- Handlers - Contain actions triggered after a specific event (e.g., service restart).
- Meta - Contains information about the role's author, dependencies, and supported platforms.
- Tasks - The core of the role; includes a list of tasks to execute.
- Templates - Contains Jinja2 templates for configuration files with variables.
- Vars - Holds variables with higher priority than defaults (not easily overridden).
You can create a new ansible role using:
ansible-galaxy init <role_name> --offline
Remember that Ansible roles should be written inside: /etc/ansible/roles/
Demo: Creating and Using an Ansible Role
Let's walk through an example role that installs and configures Apache on remote hosts.
Step 1: Create the Role
ansible-galaxy init apache --offline
Step 2: Add Tasks
Inside roles/apache/tasks/main.yml:
---
- import_tasks: install.yml
- import_tasks: configure.yml
- import_tasks: service.yml
install.yml
---
- name: Install Apache
apt:
name: apache2
state: present
configure.yml
---
- name: Copy apache configuration file
copy:
src: apache2.conf
dest: /etc/apache2/apache2.conf
notify: restart apache
service.yml
---
- name: Start and enable Apache service
service:
name: apache2
state: started
enabled: yes
Step 3: Add Handlers
Inside roles/apache/handlers/main.yml:
---
- name: restart apache
service:
name: apache2
state: restarted
Step 4: Create Files and Templates
Place your configuration file (apache2.conf) and HTML content in the files folder.
Step 5: Add Role Metadata
Inside roles/apache/meta/main.yml:
---
author: ActiveServers Team
description: Role to install and configure Apache web server
Step 6: Use the Role in a Playbook
Create a playbook named site.yml:
---
- hosts: servers
become: yes
roles:
- apache
Step 7: Validate and Run
Run a syntax check before execution: ansible-playbook site.yml --syntax-check
Execute the playbook: ansible-playbook site.yml
Conclusion
AAnsible Roles bring order and efficiency to your automation strategy. They make your playbooks modular, reusable, and scalable - a must for any production-ready DevOps environment.