Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 29 ยท Structuring Automation

Roles and Project Layout

Organize Ansible automation with roles: the role directory structure, defaults versus vars, handlers and templates, import_role versus include_role, ansible-galaxy init and a repo layout.

A single playbook with fifty tasks is easy to start and painful to keep. You scroll to find the nginx tasks, copy them into another playbook for a second project, and the two copies drift apart. A role is Ansible's unit of reuse: a folder with a fixed layout that bundles tasks, default variables, handlers, templates and files for one job, such as "install and configure nginx". Playbooks then shrink to a list of roles per group of hosts.

This lesson shows the role directory structure, the difference between defaults/ and vars/, how to call roles in different ways, how ansible-galaxy init scaffolds one, and a repository layout that scales. It builds on Handlers, Tags and Task Control and Variables, Facts and Precedence.

Real Ansible cannot run on this site, so the YAML and directory trees are read-only. The runnable examples are JavaScript stand-ins that model how a role tree turns into an ordered list of steps. They illustrate the idea, not Ansible's loader.

Anatomy of a role

A role lives in a directory named after the role, normally under roles/ next to your playbook. Ansible looks for specific subfolders; each one is optional, and a main.yml file in it is the entry point.

TEXT
roles/
  nginx/
    defaults/main.yml     # default variables, easy to override (lowest precedence)
    vars/main.yml         # internal variables, hard to override
    tasks/main.yml        # the tasks the role runs
    handlers/main.yml     # handlers the tasks can notify
    templates/            # Jinja2 files for the template module
    files/                # static files for the copy module
    meta/main.yml         # role metadata and dependencies
    README.md

When you use the role, Ansible loads these pieces automatically. Tasks inside the role can refer to templates/site.conf.j2 as just site.conf.j2, and to files/banner.txt as banner.txt, with no paths. A tiny role could be this:

YAML
# roles/nginx/defaults/main.yml
http_port: 80
site_name: example.local

# roles/nginx/tasks/main.yml
- name: Install nginx
  ansible.builtin.package:
    name: nginx
    state: present

- name: Write the site config
  ansible.builtin.template:
    src: site.conf.j2
    dest: /etc/nginx/conf.d/{{ site_name }}.conf
    mode: "0644"
  notify: Reload nginx

- name: Start nginx
  ansible.builtin.service:
    name: nginx
    state: started
    enabled: true

# roles/nginx/handlers/main.yml
- name: Reload nginx
  ansible.builtin.service:
    name: nginx
    state: reloaded

Handlers defined in a role are available to the role's tasks, and they follow the same "once, at the end" rule as before.

defaults versus vars

Both folders hold variables, but they send different messages.

  • defaults/main.yml is the role's public settings. These are the weakest variables in the whole precedence list, so inventory, group_vars, play vars and -e can all override them. Put every knob a user might want here, with a sensible value.
  • vars/main.yml is for values the role needs internally, such as a package name per OS family. These rank high: play vars and inventory variables no longer override them. Only extra vars (-e) and a few task-level settings win.

A good rule: if the caller should be able to change it, it goes in defaults. If changing it would break the role, put it in vars. Beginners often put everything in vars/ and then wonder why group_vars seem ignored.

Stand-in: from role tree to run order

The object below describes two roles the way the directory tree would. The stand-in resolves meta dependencies first, lists the tasks in order, and merges variables by precedence.

JS Load a role tree into a run order

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The play overrides http_port from the role's defaults. Add http_port: 9000 to roles.nginx.vars and run again: now the role's own vars wins over the play, which shows why vars/ is the wrong place for settings you want to be overridable.

Using roles in a playbook

There are three ways to call a role. The classic one is the roles keyword:

YAML
- hosts: web
  roles:
    - common
    - role: nginx
      vars:
        http_port: 8080
      tags: web

Roles listed this way run before the play's own tasks. Passing vars here sets them as role parameters, which rank above most other variables.

For control over the order, use tasks:

YAML
- hosts: web
  tasks:
    - name: Prepare the base system
      ansible.builtin.import_role:
        name: common

    - name: Configure nginx only on Debian-like hosts
      ansible.builtin.include_role:
        name: nginx
      when: ansible_facts['os_family'] == "Debian"

The difference between the two is when Ansible reads the role:

  • import_role is static. Ansible reads the role's tasks when it parses the playbook, so --list-tasks, tags and --start-at-task see them. A when on the import is copied onto every task inside.
  • include_role is dynamic. Ansible reads the role only when execution reaches that line, so you can include it in a loop, or pick the role name from a variable. Tags on the include itself do not reach the inner tasks unless you use apply.

As a rule of thumb: use roles: or import_role by default, and include_role when you need loops or a name computed at runtime.

Stand-in: static versus dynamic

The model shows the practical consequence: an import is visible before the run, while an include decides during the run.

JS import_role versus include_role

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Dependencies and scaffolding

A role can depend on other roles through meta/main.yml. Dependencies run first:

YAML
# roles/nginx/meta/main.yml
dependencies:
  - role: common

Dependencies are convenient but can hide order, so many teams prefer to list roles explicitly in the playbook. Ansible runs a given role only once per play even if several roles depend on it, unless it is called with different parameters.

The ansible-galaxy tool creates the skeleton for you:

Terminal
ansible-galaxy role init roles/nginx

It writes every folder above, with a stub main.yml in each and a README.md. Delete the folders you do not need, because empty ones add noise. Galaxy and sharing roles are covered in Collections, Galaxy and Reusable Content.

A project layout that scales

TEXT
ansible-project/
  ansible.cfg
  inventories/
    dev/
      hosts.ini
      group_vars/
      host_vars/
    production/
      hosts.ini
      group_vars/
      host_vars/
  playbooks/
    site.yml            # imports the other playbooks
    web.yml
    database.yml
  roles/
    common/
    nginx/
    postgresql/
  collections/
    requirements.yml

Each environment has its own inventory directory, so ansible-playbook -i inventories/production playbooks/site.yml uses production data with the same roles and playbooks. Playbooks are thin: they map host groups to roles. Roles contain the logic. The inventory lesson covers the group and host variable folders, and the final projects put a full layout together (see Project: Multi-Tier Stack with Roles and Vault).

flowchart TD
  P["playbook site.yml"] --> G1["play: hosts web"]
  P --> G2["play: hosts db"]
  G1 --> R1["role common"]
  G1 --> R2["role nginx"]
  G2 --> R1
  G2 --> R3["role postgresql"]
  R2 --> D["defaults, tasks, handlers,<br/>templates, meta"]

A playbook maps host groups to roles; each role bundles its own tasks, defaults, handlers and templates.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A setting that callers should be able to change from group_vars belongs in which role folder?

    defaults has the lowest precedence of all variables, so inventory, play vars and -e can override it. vars/main.yml ranks much higher and is hard to override.
  2. 2. What is the main difference between import_role and include_role?

    Static imports are visible to --list-tasks and tags; dynamic includes can be looped or chosen at runtime.
  3. 3. In which directory do you put a Jinja2 file that a role's template task uses?

    The template module searches the role's templates directory, so src can be just the file name.
  4. 4. What does ansible-galaxy role init roles/nginx do?

    init only scaffolds folders and stub files; it does not run or download anything.

Summary

  • A role bundles tasks, defaults, vars, handlers, templates, files and metadata in a fixed directory layout, and playbooks just list roles per host group.
  • defaults/ holds overridable settings (lowest precedence); vars/ holds internal constants (high precedence).
  • Call roles with roles: (runs before tasks), import_role (static) or include_role (dynamic).
  • meta/main.yml can declare dependencies; ansible-galaxy role init creates the skeleton.
  • A scalable project has per-environment inventories, thin playbooks and reusable roles.

Next: Collections, Galaxy and Reusable Content.