Loading

Quipoin Menu

Learn • Practice • Grow

ansible / Ansible Roles
tutorial

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.md

Creating a Simple Role

Initialize a role called nginx:
ansible-galaxy init nginx
Edit 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: yes
Add a handler in nginx/handlers/main.yml:
- name: restart nginx
service:
name: nginx
state: restarted
become: yes

Using a Role in a Playbook

Create a playbook site.yml:
---
- name: Apply nginx role to webservers
hosts: webservers
roles:
- nginx
Run 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: 8080


Two Minute Drill
  • Roles organize tasks, handlers, vars, and templates into reusable components.
  • Use ansible-galaxy init rolename to create a role skeleton.
  • Apply roles in a playbook using the roles keyword.
  • Variables can be set in defaults/ (low priority) or vars/ (high).

Need more clarification?

Drop us an email at career@quipoinfotech.com