Roles & reuse
Package automation into shareable units.
As playbooks grow, you factor them into roles — the standard way to package and reuse Ansible automation. A role is a directory with a fixed layout: tasks/, templates/, files/, handlers/, defaults/ (overridable variables), and vars/. You then include a role in a play with one line, and it brings its whole implementation. Roles are how a “webserver” or “baseline hardening” capability becomes a shareable, versioned unit.
- name: Install nginxansible.builtin.apt: { name: nginx, state: present }- name: Render configansible.builtin.template: { src: nginx.conf.j2, dest: /etc/nginx/nginx.conf }notify: reload nginx---# site.yml uses it in one line:- hosts: webbecome: trueroles:- nginx
Sharing roles
You do not write every role yourself. Ansible Galaxy is the public registry of community roles and collections, installed with ansible-galaxy, and organizations keep private ones. A requirements file pins the roles and collections a project needs, so ansible-galaxy install reproduces the exact set — the same dependency-pinning discipline as any package manager, which matters because a role runs with privilege on your hosts.
roles:- name: geerlingguy.nginxversion: "3.1.4" # pin itcollections:- name: community.cryptoversion: "2.16.0"# ansible-galaxy install -r requirements.yml