Ansible Roles
As playbooks grow, they become hard to manage. Roles provide a way to organize tasks, handlers, variables, and templates into reusable, shareable components. A role is like a mini‑playbook with a standard directory structure.
What Is a Role?
A role is a set of files that encapsulate a specific function – e.g., installing and configuring nginx, setting up a database, or deploying an application. Roles promote reuse and clean separation of concerns.
Roles are the building blocks for reusable Ansible automation.
Role Directory Structure
Create a role using
ansible-galaxy init role_name. The typical structure:rolename/
├── tasks/ # main.yml – list of tasks
├── handlers/ # main.yml – handlers
├── templates/ # .j2 files
├── files/ # static files
├── vars/ # main.yml – high‑priority variables
├── defaults/ # main.yml – default variables (lowest priority)
├── meta/ # dependencies and metadata
└── README.mdCreating a Simple Role
Initialize a role called
nginx:ansible-galaxy init nginxEdit nginx/tasks/main.yml:---
- name: Install nginx
apt:
name: nginx
state: present
become: yes
- name: Start nginx
service:
name: nginx
state: started
enabled: yes
become: yesAdd a handler in nginx/handlers/main.yml:- name: restart nginx
service:
name: nginx
state: restarted
become: yesUsing a Role in a Playbook
Create a playbook
site.yml:---
- name: Apply nginx role to webservers
hosts: webservers
roles:
- nginxRun the playbook. Ansible automatically includes tasks, handlers, etc., from the role.Role Variables and Defaults
Define default variables in
defaults/main.yml (lowest priority) and mandatory variables in vars/main.yml. Override them in the playbook:roles:
- role: nginx
vars:
nginx_port: 8080Two Minute Drill
- Roles organize tasks, handlers, vars, and templates into reusable components.
- Use
ansible-galaxy init rolenameto create a role skeleton. - Apply roles in a playbook using the
roleskeyword. - Variables can be set in
defaults/(low priority) orvars/(high).
Need more clarification?
Drop us an email at career@quipoinfotech.com
