Why Roles?
As playbooks grow, managing hundreds of tasks becomes difficult. Roles provide reusable, modular automation structures. [docs.ansible.com]
Create a Role
ansible-galaxy role init nginx
Generated structure:
nginx/
├── defaults
├── files
├── handlers
├── meta
├── tasks
├── templates
├── vars
Main Task Example
tasks/main.yml
---
- name: Install nginx
apt:
name: nginx
state: present
Using Roles
---
- hosts: webservers
roles:
- nginx
``
Download Community Roles
Search:
ansible-galaxy role search nginx
Install:
ansible-galaxy role install geerlingguy.nginx
Use:
roles:
- geerlingguy.nginx
Collections
Modern Ansible packages automation content as collections containing modules, plugins, playbooks, and roles. [docs.ansible.com], [docs.ansible.com]
Install:
ansible-galaxy collection install community.general
Best Practices
- Build reusable roles.
- Store dependencies in
requirements.yml. - Use collections instead of custom code when possible.
- Follow the standard role directory structure.







