CoursesAnsibleIntermediate

Roles & reuse

Package automation into shareable units.

Intermediate12 min · lesson 7 of 12

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.

roles/nginx/tasks/main.yml
- name: Install nginx
ansible.builtin.apt: { name: nginx, state: present }
- name: Render config
ansible.builtin.template: { src: nginx.conf.j2, dest: /etc/nginx/nginx.conf }
notify: reload nginx
---
# site.yml uses it in one line:
- hosts: web
become: true
roles:
- 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.

requirements.yml
roles:
- name: geerlingguy.nginx
version: "3.1.4" # pin it
collections:
- name: community.crypto
version: "2.16.0"
# ansible-galaxy install -r requirements.yml
A downloaded role runs with your privileges
A role from Galaxy executes on your hosts with whatever become rights you grant — so an unpinned or unreviewed community role is a supply-chain risk exactly like an npm package. Pin versions, review what a role does before adopting it (especially any that run shell or download binaries), and prefer well-maintained sources. Convenience does not suspend supply-chain caution.