Skip to content

Lesson 9 of 13 · 22m

Roles and Collections: The Units of Reuse

The role directory contract, defaults vs vars, dependency semantics, and when a role earns its own repo.

A playbook that does everything is a bash script that learned YAML. We've all written it — two hundred lines of tasks that install postgres, configure nginx, set sysctl, deploy the app, in one file, runnable top to bottom and nothing else. Roles are how Ansible actually scales past that: a role is a directory with a contract. Put tasks in tasks/, defaults in defaults/, handlers in handlers/ — and any playbook anywhere can consume it by name. Write "install postgres" once as a role and you never write it again.

The directory contract

roles/
  postgres/
    tasks/main.yml       # the work — always the entry point
    handlers/main.yml    # restart/reload logic
    defaults/main.yml    # overridable knobs: postgres_version: 15
    vars/main.yml        # internal constants: repo URL, unit name
    files/               # static payloads for copy:
    templates/           # .j2 for template:
    meta/main.yml        # dependencies, galaxy_info
    molecule/            # verification lives here

Consume it by name and the pieces wire themselves:

- hosts: dbservers
  roles:
    - role: postgres
      vars:
        postgres_version: 16
        postgres_max_connections: 400

Ansible resolves tasks/main.yml plus the named subdirectories — a template: inside the role finds templates/foo.j2 without a path; copy: finds files/. That's the whole magic: convention in place of configuration.

defaults vs vars: the contract boundary people get backwards

defaults/main.yml sits at the bottom of variable precedence — every value there is a public API the caller may override via group_vars, play vars, or -e. vars/main.yml sits near the top — above inventory, above play vars — for things callers must not change: the package name, the service unit, the repo URL.

Backwards is the most common role bug in the wild: a "configurable" postgres_port: 5432 placed in vars/ silently outranks the operator's host_vars override, the play runs green, and the port never changes. The test is one line: if an operator should tune it, it belongs in defaults/; if changing it breaks the role, it belongs in vars/.

meta/main.yml: dependencies that run first

# roles/postgres/meta/main.yml
galaxy_info:
  author: acme-ops
  description: PostgreSQL server, hardened baseline
  role_name: postgres
dependencies:
  - role: common
    vars: { common_sysctl_tier: database }

dependencies: run before the role — postgres needing common (the baseline role) first is the real-world pattern. The dedup rule matters: a role runs once per play with the same parameter set — diamond dependency graphs don't reinstall the world, but two paths passing different vars do run it twice, and that's a design signal, not a convenience.

Import order, stated precisely

In a play that uses roles:: pre_tasks: → role dependencies and roles → tasks: → post_tasks: → handlers. import_role is static (resolved at parse time, tags propagate cleanly); include_role is dynamic — it can be looped, wrapped in when, given fresh vars per call, which is also how you invoke a role in the middle of a task list instead of at play top.

Collections: the distribution unit, not the reuse unit

Roles are what you write for reuse. Collections are how content gets distributed and versioned — a namespace.collection tarball that can hold modules, plugins, roles, and docs as one installable unit: community.general.haproxy, ansible.posix.firewalld, amazon.aws.ec2_instance. The distinction is worth keeping straight because the mental models differ: a role is a directory contract you own; a collection is a versioned artifact you pin in requirements.yml and install with ansible-galaxy collection install -r requirements.yml.

Galaxy is a public registry, and it behaves like one — a collection ships arbitrary modules that execute on your nodes. The pinning discipline from the packaging lesson applies double here: pin versions in requirements.yml, review what lands in collections/, and for anything that configures a security boundary, read the role's tasks before you let it run.

When a role earns its own repo

Inside one project, roles/ in the repo wins — same checkout, same review, same CI, no versioning hell. A role graduates to its own repo (and a requirements.yml entry, maybe its own Molecule suite) when two things are true: it has consumers across repositories, and it has an owner who'll version it. Extracted too early, it rots as "the role repo nobody updates"; kept too long in a monorepo, it accretes project-specific vars/ until it's not reusable.

Field notes

  • Role independence is the test: if postgres can't converge a bare VM alone, it has hidden coupling — usually a fact or a var it assumed some earlier play would set.
  • ansible-galaxy init roles/postgres scaffolds the skeleton; the interesting directories are tasks/, defaults/, handlers/, templates/, meta/ — delete the ones you don't use.
  • meta/main.yml's dependencies are for ordering, not reuse — a role that needs another role's code should be restructured, not chained.

Was this lesson helpful?

Sign in to rate

Keep reading

Related articles from the SudoSecurity blog.