At the end of Module 3, Aurora Store is configured end to end with ansible-playbook site.yml, but its playbooks have grown to the point of becoming hard to manage: webservers.yml mixes, in some twenty tasks, the nginx installation, the store website, the firewall and the database connection details; none of that code can be reused in another project without copying and pasting, and testing one part on its own is almost impossible. Roles are Ansible's answer to this problem: a standard way of packaging tasks, variables, files and templates into independent, reusable units that are easy to share. In this lesson you'll learn exactly what a role is, what advantages it brings, how it differs from a playbook and from a collection, how a playbook consumes it and, above all, you'll design the plan for turning Aurora's playbooks into the common, nginx, postgresql and aurora_app roles. You won't create any role yet: first you need to decide carefully what goes into each one.
- The problem with large playbooks
Review the task list you ended Module 3 with:
play #1 (webservers): Configure the Aurora Store web servers TAGS: []
tasks:
Update the package cache if it is older than one hour TAGS: []
Install nginx TAGS: []
Create the web root directory TAGS: []
Publish the store home page TAGS: []
Publish the store static pages TAGS: []
Configure the Aurora site in nginx TAGS: []
Enable the Aurora site TAGS: []
Disable the default nginx site TAGS: []
Ensure nginx is started and enabled TAGS: []
Reload nginx if its configuration has changed (temporary) TAGS: []
Allow SSH through the firewall TAGS: []
Allow HTTP through the firewall TAGS: []
Enable the firewall TAGS: []
Compute the database connection string TAGS: []
Create the Aurora configuration directory TAGS: []
Publish the database connection details TAGS: []
Wait for the store website to respond TAGS: []
Get the nginx version TAGS: []
Show the nginx version TAGS: []
Check that the store website works TAGS: []It works, it's idempotent and it verifies itself. But picture Aurora's next few months:
- A second project: the marketing team wants a blog on another server running nginx. Do you copy the nginx tasks from
webservers.yml? Then you'll have two copies to maintain, and when you fix a bug in one you'll forget about the other. - Mixed responsibilities: the web server (nginx), the application (the store page), security (the firewall) and the database integration all live in the same file. To change one thing you have to read all of them.
- Ownerless variables:
aurora_web_root,nginx_portandaurora_static_pagesare in the inventory, but nothing tells you which tasks use them or which values are mandatory. Anyone new to the project will have to read all the code to find out. - Hard to test: you can't check "just nginx" on a test machine without dragging along the rest of the playbook (you'll do it with Molecule in Lesson 9.5, and Molecule works precisely with roles).
- Hard to share: there's no standard way of publishing "the PostgreSQL part" for another team to use.
These aren't Ansible problems but organizational ones: the same thing happens to any program that grows in a single file. In programming they're solved with functions and modules; in Ansible, with roles.
- What a role is
A role is a set of tasks, variables, files, templates, handlers and metadata organized in a standard directory structure, with a name, that a playbook can apply to a group of hosts. This is, in simplified form, the nginx role you'll create in Lesson 4.3:
roles/
└── nginx/ ← the role's name is the directory's name
├── tasks/
│ └── main.yml ← the role's tasks (entry point)
├── defaults/
│ └── main.yml ← variables with their default value (the "parameters")
├── files/
│ └── gzip.conf ← files the role copies to the servers
└── meta/
└── main.yml ← metadata: author, license, dependenciesThe key idea is convention over configuration: you don't have to tell Ansible where the role's tasks or variables are; it looks for them in directories with fixed names (tasks/main.yml, defaults/main.yml…). Each directory has a specific purpose, and you'll study them all in depth in Lesson 4.3.
A good way to understand a role is to compare it with a function in a programming language:
| Function | Ansible role |
|---|---|
| Function name | Name of the role's directory (nginx) |
| Function body | The tasks (tasks/main.yml) |
| Parameters with a default value | Variables in defaults/main.yml (nginx_port: 80) |
| Internal constants | Variables in vars/main.yml |
| Call with arguments | Applying the role in a playbook with other values (nginx_port: 8080) |
| Documentation and argument validation | README.md and meta/argument_specs.yml (Lesson 4.6) |
| Importing another function it needs | Dependencies in meta/main.yml (Lesson 4.6) |
Just like a good function, a good role does one thing, does it well, receives everything that can vary as parameters and doesn't depend on external details it doesn't declare.
- Advantages of working with roles
| Advantage | What it means | Example in Aurora |
|---|---|---|
| Reuse | The same role works for many playbooks, projects and environments, changing only its variables | The nginx role will be able to serve the store and, tomorrow, the marketing blog |
| Encapsulation | The role hides the details; whoever uses it only needs to know its variables | To change the port, nginx_port is enough, without reading the tasks |
| Organization | Everything has its standard place; anyone who knows Ansible knows where to look | The PostgreSQL tasks will be in roles/postgresql/tasks/ |
| Sharing | Roles are published and installed with ansible-galaxy (Module 6) |
Another team could install your postgresql role from a Git repository |
| Testing | A role can be tested in isolation on a disposable machine (Lesson 9.5) | Testing nginx without touching the database |
| Teamwork | Each role can have its own owner and evolve separately | Operations maintains common; development, aurora_app |
| Readable playbooks | Playbooks shrink to "which roles go on which hosts" | webservers.yml will go from twenty tasks to a list of roles and a few checks |
The last advantage is the one you notice most day to day. Compare the current webservers.yml with what it will look like at the end of the module:
---
- name: Configure the Aurora Store web servers
hosts: webservers
become: true
roles:
- nginx
- aurora_app
post_tasks:
# ... the website checks, as in Lesson 3.7 ...Just by reading that, you already know what is done on the web servers. The how is inside each role.
- Roles, playbooks and collections
You already know playbooks (Module 3) and collections (Lesson 2.6). It's easy to confuse the three concepts, so it's worth pinning down the differences:
| Aspect | Playbook | Role | Collection |
|---|---|---|---|
| What it is | A YAML file with a list of plays | A directory with tasks, variables, files… | A distribution package for Ansible content |
| What it contains | Plays: hosts + tasks and/or roles | Tasks, handlers, variables, files, templates, metadata | Modules, plugins, roles and playbooks |
| Is it run directly? | Yes: ansible-playbook site.yml |
No: a play applies it | No: its content (modules, roles…) is used |
| Does it decide which hosts it acts on? | Yes (hosts:) |
No: it acts on the hosts of the play that uses it | No |
| Answers the question | What is applied, where and in what order? | How is a component configured? | How do I distribute and version a set of content? |
| How it's shared | The project's Git repository | Git or Galaxy (ansible-galaxy role install) |
Galaxy or Automation Hub (ansible-galaxy collection install) |
| Example in Aurora | site.yml, webservers.yml |
nginx, postgresql |
community.postgresql, which you already use |
A few ideas to keep them apart:
- The playbook orchestrates, the role implements. The playbook says "apply the
nginxrole to the hosts in thewebserversgroup"; the role knows how to install and configure nginx, but it doesn't know (and shouldn't know) which servers it will be applied to. - A collection can contain roles. When you installed
community.postgresqlyou got modules; other collections include complete roles, which are used with their fully qualified name (for example,namespace.collection.role). You'll create your own collection in Lesson 6.5. - Roles don't replace the inventory. The data about your infrastructure (IPs, domain, team users) stays in
inventory/; the role receives that data through its variables.
- How a playbook consumes roles
A play applies roles with the roles: keyword, which already appeared in the keyword table in Lesson 3.4:
When you run it, Ansible:
- Looks for a directory called
commonin the role paths: first in aroles/directory next to the playbook, then in the paths of theroles_pathoption inansible.cfg(Lesson 4.2). - Loads its default variables (
defaults/main.yml), its internal variables (vars/main.yml), its handlers and its metadata. - Runs its tasks (
tasks/main.yml) on the play's hosts, just as if they were written in the play itself. In the output, each task is prefixed with the role's name:TASK [common : Set the time zone].
flowchart LR
P["site.yml<br/>(playbook)"] --> PL["Play<br/>hosts: aurora<br/>roles: [common]"]
PL --> R["roles/common/"]
R --> D["defaults/main.yml<br/>default values"]
R --> V["vars/main.yml<br/>internal variables"]
R --> T["tasks/main.yml<br/>tasks"]
R --> M["meta/main.yml<br/>metadata and dependencies"]
T --> H["web1, web2, db1"]
Besides roles:, there are two modules for using roles as if they were tasks, in the middle of a task list: ansible.builtin.import_role (static) and ansible.builtin.include_role (dynamic). You'll meet them in Lesson 4.5. In Lesson 4.4 you'll study the roles: keyword in depth: how to pass parameters, in what order it runs relative to pre_tasks, tasks and post_tasks, and what happens if you apply the same role twice.
- Criteria for designing a good role
Turning a playbook into roles isn't just moving tasks around. Design decisions determine whether the roles will really be reusable. These are the criteria Aurora will follow:
- One responsibility per role.
nginxmanages nginx; it doesn't publish the store website or configure PostgreSQL. If you need the phrase "and also" to describe a role, it's probably two roles. - Everything variable goes in variables. Paths, ports, names and lists are defined as variables with a sensible default value in
defaults/main.yml. The tasks contain no hardcoded Aurora data. - Variables carry the role's prefix. All of a role's variables start with its name:
nginx_port,postgresql_users,common_timezone. As you'll see in Lesson 4.2, role variables are shared with the whole play, and without a prefix two roles could overwrite each other'sportvariable. - The role doesn't know the inventory. A role shouldn't write
groups['webservers']orhostvars['db1']: if it needs to know something about the inventory, it receives it through a variable that the inventory fills in. - Idempotent and self-sufficient. Applying the role twice changes nothing the second time, and the role installs everything it needs (for example, it updates the package cache before installing) without relying on someone having done it earlier.
- Explicit dependencies. If a role needs another, it declares it (Lesson 4.6) or documents it; it doesn't silently take it for granted.
The split of responsibilities in the project looks like this:
| Piece | Responsibility | Where it lives in Aurora |
|---|---|---|
| Inventory | Data: which servers exist and what values our variables have | inventory/ |
| Roles | Reusable logic: how each component is configured | roles/ |
| Playbooks | Orchestration: which roles go on which host groups and in what order, plus the final checks | site.yml, common.yml, dbservers.yml, webservers.yml |
- Aurora Store refactoring plan
With those criteria in mind, go through the current tasks and assign each one to its future home:
| Current tasks | Current file | Destination |
|---|---|---|
Common packages, time zone, team users, motd, local facts |
common.yml |
common role |
Install PostgreSQL, parameters (conf.d/aurora.conf), service, users, databases, pg_hba |
dbservers.yml (tasks) |
postgresql role |
| Check that PostgreSQL accepts connections | dbservers.yml (post_tasks) |
Stays in the playbook (post_tasks) |
| Install nginx, configure and enable the site, default site, service, firewall | webservers.yml (tasks) |
nginx role |
| Web root directory, home page, static pages, database connection details | webservers.yml (tasks) |
aurora_app role |
Wait for the website, nginx version, assert |
webservers.yml (post_tasks) |
Stays in the playbook (post_tasks) |
Update the package cache (pre_tasks) |
dbservers.yml, webservers.yml |
Inside each role's installation tasks |
Notice the separation between nginx and aurora_app: nginx is a generic component (it serves a store just as well as a blog), whereas the store website and its connection details are specific to Aurora. Separating them is what will make it possible to reuse nginx. In return, aurora_app needs nginx for its content to be served: that's the dependency relationship you'll declare in Lesson 4.6.
And the final checks (post_tasks) stay in the playbooks: they verify the result of this particular deployment and are part of the orchestration.
The target architecture at the end of the module:
flowchart TD
S["site.yml"] --> C["common.yml<br/>hosts: aurora"]
S --> D["dbservers.yml<br/>hosts: dbservers"]
S --> W["webservers.yml<br/>hosts: webservers"]
C --> RC["common role"]
D --> RP["postgresql role"]
W --> RN["nginx role"]
W --> RA["aurora_app role"]
RA -. "depends on (Lesson 4.6)" .-> RN
I["inventory/<br/>Aurora data"] -. "variables" .-> RC
I -. "variables" .-> RP
I -. "variables" .-> RN
I -. "variables" .-> RA
The module roadmap:
| Lesson | What you'll do in aurora-infra |
|---|---|
| 4.2 Creating Roles | Create roles/common from common.yml, rename its variables with the common_ prefix and configure roles_path |
| 4.3 Role Directory Structure | Create roles/nginx and roles/postgresql from webservers.yml and dbservers.yml, using files/ and vars/ |
| 4.4 Using Roles in Playbooks | Create roles/aurora_app and rewrite the playbooks with roles: |
| 4.5 Reusing Tasks: include and import | Split the nginx and postgresql tasks into several files and load variables according to the distribution |
| 4.6 Role Dependencies and Argument Validation | Declare that aurora_app depends on nginx, validate the roles' variables and document them |
There's a golden rule you'll follow at every step: a refactoring must not change the servers. The VMs have been configured by site.yml since the end of Module 3; after turning each playbook into roles, you'll run ansible-playbook site.yml and the result must be changed=0 on every host. If anything comes out changed, you've altered the behavior by accident (a file with a different space, a variable with another value) and you'll know instantly. Idempotency, which until now was a desirable property, becomes your regression test.
- Write your own roles or use the community's?
There are thousands of roles published on Ansible Galaxy: for nginx, PostgreSQL, users, firewalls… Why write your own?
- To learn: writing roles is the best way to understand how the ones you download later work.
- Because they're small: Aurora's roles will do exactly what Aurora needs, without dozens of options you don't use.
- Because community code also has to be evaluated: quality, maintenance, license, security. You'll learn to search for, evaluate and install third-party roles in Module 6.
In real projects the usual approach is a mix: community roles for very standard, well-maintained components, and your own roles for what's specific to the organization (like aurora_app).
Common Mistakes and Tips
- The "role that does everything": creating a single
aurorarole with all the project's tasks just moves the problem to another directory. Split by responsibility. - Roles that are too small: one role per task (
install_nginx,enable_site…) multiplies complexity without providing real reuse. A role should represent a complete component. - Project data inside the role: writing
aurora-store.exampleor/var/www/aurorain the tasks prevents the role from being reused. Those values go in the inventory, and the role receives them through variables. - Roles that read the inventory directly:
groups['dbservers'][0]inside a role ties it to one specific project's group names. Pass it the data through a variable. - Confusing role and collection: a role can't cleanly contain distributable custom modules, nor is it versioned as a package; that's what collections are for (Lesson 6.5).
- Tip: before creating a role, write in one sentence what it does and which variables it receives. If the sentence is long or confusing, the design will be too.
Exercises
Exercise 1: Classifying the database tasks
Open dbservers.yml and, for each task (including pre_tasks and post_tasks), state whether it will go to the postgresql role, stay in the playbook or disappear. Justify each decision.
Exercise 2: Spotting what prevents reuse
Go through the webservers.yml tasks that will go to the nginx role and make a list of every value hardcoded in them or read from Aurora-specific variables that would prevent using them as they are for the marketing blog (another domain, another directory, no firewall). For each one, propose the name of a role variable.
Exercise 3: Playbook, role or collection?
State which piece (playbook, role or collection) you would use in each case:
- Distributing across the whole company a set of custom modules for managing the internal payments API, together with two roles that use them.
- Defining that the servers in the
webserversgroup get nginx and the store website, and then checking that the website responds. - Packaging the configuration of a Redis server with its port and maximum memory as parameters.
Solutions
Exercise 1.
| Task | Destination | Reason |
|---|---|---|
Update the package cache (pre_tasks) |
postgresql role (inside the installation) |
The role must be self-sufficient: it can't rely on the play updating the cache |
| Install PostgreSQL and the dependencies | postgresql role |
It's the core of the component |
| Configure the PostgreSQL parameters | postgresql role |
Configuration of the component, with values from variables |
| Restart PostgreSQL if its configuration has changed (temporary) | postgresql role |
It goes with the configuration; in Lesson 5.1 it will become a handler of the role |
| Ensure PostgreSQL is started and enabled | postgresql role |
State of the service |
| Create the users / the databases | postgresql role |
The data (postgresql_users, postgresql_databases) already comes from the inventory |
| Allow the web servers access | postgresql role |
But without groups['webservers'] inside: the list of clients will arrive through a variable |
| Reload PostgreSQL if access control has changed (temporary) | postgresql role |
Same as the restart |
Check that PostgreSQL accepts connections (post_tasks) |
Playbook | Final verification of this deployment |
Exercise 2. Values that prevent reusing the nginx tasks, and proposed variables:
| Current value | Problem | Proposed variable |
|---|---|---|
File name aurora in sites-available/sites-enabled |
The blog would have to be called "aurora" | nginx_site_name |
server_name {{ aurora_domain }} www.{{ aurora_domain }} |
Uses an Aurora project variable | nginx_server_name |
root {{ aurora_web_root }} |
Same | nginx_root |
nginx_port |
It's already a variable with the role's prefix: it stays | nginx_port |
ufw tasks always active |
The blog might not want its firewall managed by this role | nginx_firewall_enabled (true/false) |
| Always disabling the default site | Another project might need it | nginx_remove_default_site |
These are, in fact, the variables the nginx role will have in Lesson 4.3.
Exercise 3. 1: a collection (it's the only piece that distributes custom modules, and it can include roles). 2: a playbook (it decides hosts, order and checks). 3: a role (it configures a component, with parameters).
Conclusion
Roles are Ansible's unit of reuse: a directory with a standard structure (tasks/, defaults/, vars/, files/, meta/…) that packages how a component is configured and receives everything that can change through variables. They bring reuse, encapsulation, organization, ease of sharing and testing, and far more readable playbooks. You've pinned down the difference between playbook (orchestrates: what, where and in what order), role (implements a component) and collection (distributes content), you've seen how a play applies roles with roles: and you've designed Aurora's plan: common, postgresql, nginx and aurora_app, with the data in the inventory and the checks in the playbooks, and with changed=0 as proof that each step of the refactoring leaves the servers untouched. In the next lesson, Creating Roles, you'll take the first step: you'll generate a role skeleton with ansible-galaxy role init, migrate common.yml to the common role, learn the difference between defaults and vars and check that the infrastructure stays exactly the same.
