Roles are how you organize and reuse Ansible at scale — a standard directory layout that bundles tasks, variables, templates, and handlers into a shareable unit.
Why: a long playbook becomes unmanageable. A role packages everything for one piece of setup — its tasks, variables, templates, files, and handlers — into a standard directory structure Ansible loads automatically. Roles make configuration reusable across projects and shareable through Ansible Galaxy.
roles/
└── nginx/
├── tasks/main.yml ← the tasks (entry point)
├── handlers/main.yml ← handlers
├── templates/ ← .j2 templates
├── files/ ← static files to copy
├── vars/main.yml ← role variables
└── defaults/main.yml ← default variables (lowest priority)Why: you do not create the directories by hand. ansible-galaxy init generates the full standard layout for a role, with empty main.yml files in each folder ready to fill. Keep roles under a roles/ directory next to your playbook.
Create the standard role skeleton
ansible-galaxy init roles/nginxSee what it generated
ls roles/nginxWhy: a role’s tasks/main.yml is just a task list — the same tasks you already write, minus the play header. Paths are relative to the role, so template: src points into the role’s templates/ folder automatically. defaults/main.yml holds overridable defaults.
# roles/nginx/defaults/main.yml
http_port: 80
# roles/nginx/tasks/main.yml
- name: Install nginx
ansible.builtin.package:
name: nginx
state: present
- name: Deploy config
ansible.builtin.template:
src: nginx.conf.j2 # found in roles/nginx/templates/
dest: /etc/nginx/nginx.conf
notify: Restart nginxWhy: a playbook applies roles to hosts with a roles: list — clean and declarative. You can pass variables to a role inline to override its defaults. The playbook becomes a short, readable description of which roles make up each kind of server.
- name: Build a web server
hosts: web
become: true
roles:
- common
- role: nginx
vars:
http_port: 8080 # override the role's default
- role: appWhy: Ansible Galaxy (galaxy.ansible.com) hosts thousands of maintained roles and collections — you rarely start from scratch. Install them with ansible-galaxy, ideally pinned in a requirements.yml so installs are reproducible, then use them like your own.
Install a role from Galaxy
ansible-galaxy role install geerlingguy.nginxInstall everything pinned in a requirements file
ansible-galaxy install -r requirements.yml