In the previous lesson you created the common role using only part of its structure: tasks/, defaults/, vars/ and meta/. A role can have quite a few more directories, each with a precise purpose and rules that Ansible applies automatically: which file it loads, where it looks for the files you copy, which metadata it reads. In this lesson you'll go through all those directories in depth, understand how Ansible resolves relative paths inside a role and what meta/main.yml contains, and apply what you've learned to Aurora Store's two big roles: you'll create nginx from webservers.yml and postgresql from dbservers.yml, with the same discipline as in Lesson 4.2 (migrate, verify changed=0 and only then improve). As a first improvement, the nginx role will distribute a file from its files/ directory.

  1. Overview of a complete role

This is what a role that used every possible directory would look like. No real role needs them all at once:

roles/example/
├── README.md               ← documentation for people
├── defaults/
│   └── main.yml            ← default variables (parameters)
├── vars/
│   └── main.yml            ← internal variables
├── tasks/
│   ├── main.yml            ← entry point for the tasks
│   └── install.yml         ← additional task files
├── handlers/
│   └── main.yml            ← the role's handlers
├── files/
│   └── gzip.conf           ← static files
├── templates/
│   └── site.conf.j2        ← Jinja2 templates
├── meta/
│   ├── main.yml            ← metadata and dependencies
│   └── argument_specs.yml  ← variable specification (Lesson 4.6)
├── library/                ← the role's custom modules
├── module_utils/           ← Python code shared by those modules
├── lookup_plugins/         ← custom plugins (also filter_plugins/, etc.)
└── tests/                  ← minimal tests

The general rule: directories that contain YAML for Ansible (tasks, handlers, defaults, vars, meta) are loaded from a file called main.yml (main.yaml or main with no extension also work). Directories that contain material for the servers (files, templates) have no main file: they're folders where Ansible looks for whatever the tasks ask for.

  1. tasks/: the tasks

It's the only directory a role needs in order to do something. When the role is applied, Ansible runs tasks/main.yml, which is a list of tasks (no hosts:, no tasks:), as you saw with common.

tasks/ can contain other task files, for example install.yml or firewall.yml. Ansible doesn't run them on their own: they only run if main.yml imports or includes them. That's how a large role is split into manageable parts, and you'll do it in Lesson 4.5. You can also ask a role to start from a file other than main.yml (tasks_from), something you'll also see in that lesson.

  1. handlers/: the handlers

It contains handlers/main.yml, with the role's handlers: special tasks that only run when another task notifies them because it has changed something, for example "reload nginx". It's exactly what you currently solve with the temporary register + when: ... is changed pattern.

Handlers are studied in Lesson 5.1. That's why you won't create the handlers/ directory in Aurora's roles yet: the "(temporary)" tasks travel as they are inside the roles and will be replaced by the role's own handlers at that point. It's enough to know that, when they exist, they'll be here, next to the code that notifies them.

  1. defaults/ and vars/: the variables

You studied them in Lesson 4.2. A reminder:

  • defaults/main.yml: the role's parameters, with the lowest precedence. The inventory, the play or whoever applies the role can change them.
  • vars/main.yml: internal variables, with high precedence. For constants that depend on the software or the operating system: package names, service names, imposed paths.

Two more details:

  • Both directories can contain other files besides main.yml, which Ansible does not load automatically. For example, vars/Debian.yml and vars/RedHat.yml with the package names for each family, which the role loads according to the system with include_vars (Lesson 4.5).
  • In modern versions of Ansible, main can also be a directory (defaults/main/) with several YAML files that are all loaded. It's useful in roles with many variables, to group them by topic.

  1. files/: files copied as they are

It contains files that the role transfers to the servers without modifying them: fixed configurations, scripts, public certificates, static pages. They're used by modules such as ansible.builtin.copy (the src parameter), ansible.builtin.script or ansible.builtin.unarchive.

- name: Publish the gzip compression configuration
  ansible.builtin.copy:
    src: gzip.conf                     # looked up in roles/nginx/files/
    dest: /etc/nginx/conf.d/gzip.conf
    owner: root
    group: root
    mode: "0644"

Notice that src is just the file name: there's no need to write roles/nginx/files/gzip.conf. The role knows where its material is (section 7).

When should you use files/ and when content:, as you've done so far?

Situation Best option
Short content that uses variables content: (for now) or a template (Lesson 5.2)
Long file without variables files/ with src:
Binary file (image, .tar.gz, certificate) files/ with src:
Content that depends on the server or the environment A template in templates/ (Lesson 5.2)

A file in files/ has an important advantage: it can be opened, edited and reviewed in Git as what it is (a .conf, a .sh), with your editor's syntax highlighting, instead of living inside a YAML block.

  1. templates/: templates

It contains Jinja2 templates (by convention, with the .j2 extension) that the ansible.builtin.template module processes before copying them: it replaces the {{ ... }} variables with their values for each host and supports conditions and loops. For example, a roles/nginx/templates/site.conf.j2 template with:

server {
    listen {{ nginx_port }};
    root {{ nginx_root }};
}

would be used like this:

- name: Configure the site in nginx
  ansible.builtin.template:
    src: site.conf.j2                  # looked up in roles/nginx/templates/
    dest: /etc/nginx/sites-available/app
    mode: "0644"

It's the natural evolution of the content: | blocks you've been using since Module 3. Jinja2 templates deserve a whole lesson (5.2), so in this module you'll stick with copy and content:, and in that lesson you'll turn the roles' configurations into templates inside their templates/ directory.

  1. How Ansible resolves relative paths inside a role

When a role task uses a relative path in src (of copy, template, script…), Ansible looks for it in a list of directories, starting with the role's own directory of the appropriate type. You can see it clearly when the file doesn't exist:

fatal: [web1]: FAILED! =>
    changed: false
    msg: |-
        Could not find or access 'gzip.conf'
        Searched in:
                /home/student/aurora-infra/roles/nginx/files/gzip.conf
                /home/student/aurora-infra/roles/nginx/gzip.conf
                /home/student/aurora-infra/roles/nginx/tasks/files/gzip.conf
                /home/student/aurora-infra/roles/nginx/tasks/gzip.conf
                /home/student/aurora-infra/files/gzip.conf
                /home/student/aurora-infra/gzip.conf on the Ansible Controller.
        If you are using a module and expect the file to exist on the remote, see the remote_src option

The search order is:

  1. The role's directory of the corresponding type: files/ for copy, script, unarchive…; templates/ for template.
  2. The root of the role.
  3. The same subdirectory next to the task file being run (tasks/files/) and that directory itself (tasks/).
  4. The same places relative to the playbook (files/ next to the playbook and the playbook's directory).

Practical consequences:

  • Always write simple relative paths (src: gzip.conf) and keep the file in the role's files/ or templates/. The role will work the same wherever you copy it.
  • If two roles have a file with the same name (files/app.conf), each one finds its own: the search always starts with the role running the task.
  • An absolute path (src: /home/student/...) isn't searched for: it's used as is. Avoid it in roles, because it would only work on your machine.
  • If you need the role's path in an expression, the role_path magic variable contains the directory of the running role.
  • The message "expect the file to exist on the remote, see the remote_src option" reminds you that src refers to the control machine. To copy a file that's already on the managed server, use remote_src: true.

  1. meta/: metadata and dependencies

meta/main.yml describes the role. It has two main parts:

---
galaxy_info:
  author: Alex Admin
  description: Installs nginx and publishes a website
  company: Aurora Store
  license: proprietary
  min_ansible_version: "2.17"
  platforms:
    - name: Ubuntu
      versions:
        - noble
  galaxy_tags:
    - web
    - nginx

dependencies: []
Field What it's for
galaxy_info.author, company Authorship
galaxy_info.description One-sentence description
galaxy_info.license License (an SPDX identifier such as MIT or GPL-3.0-or-later; proprietary for internal use)
galaxy_info.min_ansible_version Minimum Ansible version it works with
galaxy_info.platforms Supported systems and versions (Ubuntu noble = 24.04)
galaxy_info.galaxy_tags Keywords for finding the role on Galaxy
galaxy_info.role_name, namespace Name and namespace it's published under (Lesson 6.4)
dependencies Roles that must run before this one (Lesson 4.6)
allow_duplicates Whether the role can run several times in the same play (Lesson 4.4)

galaxy_info is informational at run time: Ansible doesn't check the platforms or read the description. Its value lies in documenting the role and publishing it on Galaxy, which you'll see in Lesson 6.4. The keys that do change behavior are dependencies and allow_duplicates.

The meta/ directory can also contain argument_specs.yml, a formal specification of the role's variables (type, whether it's mandatory, allowed values) that Ansible uses to validate them automatically before running the role. You'll create it in Lesson 4.6.

  1. Custom code: library/, module_utils/ and *_plugins/

A role can include its own Python code, which Ansible makes available to its tasks (and to those of roles that run later in the same play):

Directory Content Studied in
library/ Custom modules Lesson 10.1
module_utils/ Code shared by those modules Lesson 10.1
lookup_plugins/, filter_plugins/, callback_plugins/… Custom plugins Lesson 10.3

It's a quick way to add a module to a specific role, but nowadays the recommended way to distribute modules and plugins is a collection (Lesson 6.5). Aurora's roles don't need them.

  1. tests/ and README.md

  • tests/: ansible-galaxy role init generates an inventory (localhost) and a test.yml playbook that applies the role. It's a very basic starting point. Aurora's roles will be tested with Molecule (Lesson 9.5), which creates disposable machines, applies the role, checks idempotency and verifies the result; that's why you remove tests/.
  • README.md: the role's documentation for people: what it does, requirements, variables, dependencies and a usage example. You'll complete it in Lesson 4.6.

  1. Summary table

Directory / file Loaded automatically? Content Use in Aurora
tasks/main.yml Yes List of tasks All the roles
tasks/<other>.yml No (import/include) Additional tasks Lesson 4.5
handlers/main.yml Yes Handlers Lesson 5.1
defaults/main.yml Yes Parameters (minimum precedence) All the roles
vars/main.yml Yes Internal variables (high precedence) common, nginx, postgresql
vars/<other>.yml No (include_vars) Variables per operating system Lesson 4.5
files/ No (relative src:) Static files nginx (this lesson)
templates/ No (relative src:) Jinja2 templates Lesson 5.2
meta/main.yml Yes Metadata and dependencies All the roles
meta/argument_specs.yml Yes Variable specification and validation Lesson 4.6
library/, module_utils/, *_plugins/ Yes (available to the tasks) Python code Not used
tests/ No Minimal test Replaced by Molecule (Lesson 9.5)
README.md No Documentation Lesson 4.6

  1. Practice: the nginx role

Generate the skeleton and keep only what's needed. The nginx role will use tasks/, defaults/, vars/, meta/ and, in section 15, files/:

cd ~/aurora-infra
ansible-galaxy role init --init-path roles nginx
rm -r roles/nginx/handlers roles/nginx/templates roles/nginx/tests

12.1. The parameters: defaults/main.yml

Go through the nginx tasks in webservers.yml looking for what is specific to Aurora (you did this in Exercise 2 of Lesson 4.1). Each piece of data becomes a parameter with a generic default value. Write roles/nginx/defaults/main.yml:

---
# Default values for the nginx role.

# Port the site listens on.
nginx_port: 80

# Site name: file in sites-available and link in sites-enabled.
nginx_site_name: app

# Server names for the site (server_name directive). "_" accepts any name.
nginx_server_name: "_"

# Root directory of the site.
nginx_root: /var/www/html

# Disable the "default" site installed by the package.
nginx_remove_default_site: true

# Manage the ufw firewall: allow SSH and the site's port, and enable it.
nginx_firewall_enabled: false

Notice nginx_firewall_enabled: false. Enabling a firewall is a decision with consequences (it could cut off other services on the server), so a generic role should not do it by default: whoever uses it turns it on consciously. And when they do, the role also allows SSH, because enabling ufw without that rule would lock you out of the server.

12.2. The constants: vars/main.yml

The package and service names and the configuration paths are imposed by Ubuntu's nginx package: they aren't parameters, they're internal constants. Write roles/nginx/vars/main.yml:

---
# Internal variables of the nginx role (Ubuntu/Debian). Do not override.
nginx_package: nginx
nginx_service: nginx
nginx_conf_d_dir: /etc/nginx/conf.d
nginx_sites_available_dir: /etc/nginx/sites-available
nginx_sites_enabled_dir: /etc/nginx/sites-enabled

Having them in one place has an advantage you'll exploit in Lesson 4.5: if the role had to work on another distribution, only these variables would change, not the tasks.

12.3. The tasks: tasks/main.yml

Move the nginx and firewall tasks from webservers.yml into roles/nginx/tasks/main.yml, using the role's variables:

---
- name: Install nginx
  ansible.builtin.apt:
    name: "{{ nginx_package }}"
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: Configure the site in nginx
  ansible.builtin.copy:
    dest: "{{ nginx_sites_available_dir }}/{{ nginx_site_name }}"
    owner: root
    group: root
    mode: "0644"
    content: |
      # Managed by Ansible (aurora-infra). Do not edit by hand.
      server {
          listen {{ nginx_port }} default_server;
          listen [::]:{{ nginx_port }} default_server;
          server_name {{ nginx_server_name }};

          root {{ nginx_root }};
          index index.html;

          location / {
              try_files $uri $uri/ =404;
          }
      }
  register: nginx_site_config

- name: Enable the site
  ansible.builtin.file:
    src: "{{ nginx_sites_available_dir }}/{{ nginx_site_name }}"
    dest: "{{ nginx_sites_enabled_dir }}/{{ nginx_site_name }}"
    state: link
  register: nginx_site_enabled

- name: Disable the default nginx site
  ansible.builtin.file:
    path: "{{ nginx_sites_enabled_dir }}/default"
    state: absent
  when: nginx_remove_default_site
  register: nginx_default_site

- name: Ensure nginx is started and enabled
  ansible.builtin.systemd_service:
    name: "{{ nginx_service }}"
    state: started
    enabled: true

- name: Reload nginx if its configuration has changed (temporary)
  ansible.builtin.systemd_service:
    name: "{{ nginx_service }}"
    state: reloaded
  when: nginx_site_config is changed or nginx_site_enabled is changed or nginx_default_site is changed

- name: Allow SSH through the firewall
  community.general.ufw:
    rule: allow
    name: OpenSSH
  when: nginx_firewall_enabled

- name: Allow HTTP through the firewall
  community.general.ufw:
    rule: allow
    port: "{{ nginx_port }}"
    proto: tcp
  when: nginx_firewall_enabled

- name: Enable the firewall
  community.general.ufw:
    state: enabled
  when: nginx_firewall_enabled

Differences from the playbook:

  • Install nginx once again has update_cache and cache_valid_time. In the playbook, pre_tasks took care of it; a role must be self-sufficient (criterion 5 in Lesson 4.1).
  • The site is called {{ nginx_site_name }}, and its server_name and root come from role variables. The task names no longer mention Aurora.
  • Disable the default nginx site has when: nginx_remove_default_site. If it's skipped, its registered variable says skipped, and the nginx_default_site is changed test is simply false: the reload condition still works.
  • The three ufw tasks have when: nginx_firewall_enabled. The variable is a boolean; if you ever passed it with -e nginx_firewall_enabled=false (as text), use when: nginx_firewall_enabled | bool (Lesson 3.6). In Lesson 4.5 you'll group these three tasks in their own file and the condition will be written only once.
  • The "Managed by Ansible (aurora-infra)" header is kept identical on purpose: changing it would make the file change and break the changed=0 check. The templates in Lesson 5.2 offer a standard way of generating this kind of header.

12.4. The metadata: meta/main.yml

---
galaxy_info:
  author: Alex Admin
  description: Installs nginx and publishes a website, with an optional ufw firewall
  company: Aurora Store
  license: proprietary
  min_ansible_version: "2.17"
  platforms:
    - name: Ubuntu
      versions:
        - noble
  galaxy_tags:
    - web
    - nginx

dependencies: []

12.5. The inventory feeds the role

As you did with common, the inventory connects Aurora's data with the role's parameters. inventory/group_vars/webservers.yml should end up like this:

---
# Aurora Store web servers variables
aurora_web_root: /var/www/aurora
aurora_static_pages:
  robots.txt: |
    User-agent: *
    Disallow: /admin/
  status.html: |
    <p>OK</p>

# nginx role parameters
nginx_port: 80
nginx_worker_connections: 1024
nginx_site_name: aurora
nginx_server_name: "{{ aurora_domain }} www.{{ aurora_domain }}"
nginx_root: "{{ aurora_web_root }}"
nginx_firewall_enabled: true
  • nginx_port has had the role's prefix since Lesson 2.2: there's no need to rename it.
  • nginx_site_name: aurora keeps the current file names (sites-available/aurora); if you left the default value app, the role would create a new site and the old one would be orphaned.
  • nginx_server_name and nginx_root reproduce exactly what was previously hardcoded in the task.
  • nginx_worker_connections has existed since Lesson 2.2 and the role doesn't use it yet: the role doesn't manage the main nginx.conf file yet.
  • aurora_web_root and aurora_static_pages are still store data; they're used by the tasks that remain, for now, in webservers.yml.

  1. Practice: the postgresql role

ansible-galaxy role init --init-path roles postgresql
rm -r roles/postgresql/files roles/postgresql/handlers roles/postgresql/templates roles/postgresql/tests

13.1. Parameters and constants

Many PostgreSQL variables have had the postgresql_ prefix since Lesson 2.2. Write roles/postgresql/defaults/main.yml:

---
# Default values for the postgresql role.

# PostgreSQL major version installed by the distribution (16 on Ubuntu 24.04).
# It determines the configuration paths.
postgresql_version: 16

# Server parameters, in <configuration directory>/conf.d/<postgresql_conf_name>.conf
postgresql_conf_name: ansible
postgresql_listen_addresses: localhost
postgresql_port: 5432
postgresql_max_connections: 100
postgresql_shared_buffers: 128MB

# Users (PostgreSQL roles) to create: list of {name}.
postgresql_users: []

# Databases to create: list of {name, owner}.
postgresql_databases: []

# Access control (pg_hba.conf): IP addresses of the authorized clients,
# and the database, user and authentication method for those rules.
postgresql_hba_clients: []
postgresql_hba_database: all
postgresql_hba_user: all
postgresql_hba_method: scram-sha-256

And roles/postgresql/vars/main.yml:

---
# Internal variables of the postgresql role (Ubuntu/Debian). Do not override.
postgresql_packages:
  - postgresql
  - python3-psycopg2   # required by the community.postgresql modules
  - acl                # lets Ansible become the postgres user
postgresql_service: postgresql
postgresql_config_dir: "/etc/postgresql/{{ postgresql_version }}/main"

postgresql_config_dir is an internal variable built from a parameter: if the inventory changes postgresql_version, the path changes by itself. Variables are evaluated at the moment they're used (Lesson 3.5), so it doesn't matter that they're defined in different files.

13.2. The tasks

Write roles/postgresql/tasks/main.yml:

---
- name: Install PostgreSQL and the Ansible module dependencies
  ansible.builtin.apt:
    name: "{{ postgresql_packages }}"
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: Configure the PostgreSQL parameters
  ansible.builtin.copy:
    dest: "{{ postgresql_config_dir }}/conf.d/{{ postgresql_conf_name }}.conf"
    owner: postgres
    group: postgres
    mode: "0644"
    content: |
      # Managed by Ansible (aurora-infra). Do not edit by hand.
      listen_addresses = '{{ postgresql_listen_addresses }}'
      port = {{ postgresql_port }}
      max_connections = {{ postgresql_max_connections }}
      shared_buffers = {{ postgresql_shared_buffers }}
  register: postgresql_config

- name: Restart PostgreSQL if its configuration has changed (temporary)
  ansible.builtin.systemd_service:
    name: "{{ postgresql_service }}"
    state: restarted
  when: postgresql_config is changed

- name: Ensure PostgreSQL is started and enabled
  ansible.builtin.systemd_service:
    name: "{{ postgresql_service }}"
    state: started
    enabled: true

- name: Create the PostgreSQL users
  community.postgresql.postgresql_user:
    name: "{{ item.name }}"
    state: present
  become_user: postgres
  loop: "{{ postgresql_users }}"
  loop_control:
    label: "{{ item.name }}"

- name: Create the databases
  community.postgresql.postgresql_db:
    name: "{{ item.name }}"
    owner: "{{ item.owner }}"
    state: present
  become_user: postgres
  loop: "{{ postgresql_databases }}"
  loop_control:
    label: "{{ item.name }}"

- name: Allow the clients to access the database
  community.postgresql.postgresql_pg_hba:
    dest: "{{ postgresql_config_dir }}/pg_hba.conf"
    contype: host
    databases: "{{ postgresql_hba_database }}"
    users: "{{ postgresql_hba_user }}"
    address: "{{ item }}/32"
    method: "{{ postgresql_hba_method }}"
    state: present
  loop: "{{ postgresql_hba_clients }}"
  register: postgresql_hba

- name: Reload PostgreSQL if access control has changed (temporary)
  ansible.builtin.systemd_service:
    name: "{{ postgresql_service }}"
    state: reloaded
  when: postgresql_hba is changed

The important design change is in pg_hba. In dbservers.yml, the task looped over groups['webservers'] and read hostvars[item]['ansible_host']: it knew Aurora's group names. Now the role receives a list of IP addresses in postgresql_hba_clients, wherever it comes from (criterion 4 in Lesson 4.1), and adds one /32 rule (a single address) for each one. The role no longer knows that "web servers" exist.

13.3. Metadata and inventory

roles/postgresql/meta/main.yml:

---
galaxy_info:
  author: Alex Admin
  description: Installs PostgreSQL and manages its configuration, users, databases and access control
  company: Aurora Store
  license: proprietary
  min_ansible_version: "2.17"
  platforms:
    - name: Ubuntu
      versions:
        - noble
  galaxy_tags:
    - database
    - postgresql

dependencies: []

inventory/group_vars/dbservers.yml ends up like this:

---
# Variables for the Aurora Store database servers
aurora_db_name: aurora
aurora_db_user: aurora

# postgresql role parameters
postgresql_version: 16
postgresql_port: 5432
postgresql_max_connections: 100
postgresql_shared_buffers: 128MB        # group value; db1 raises it to 512MB in host_vars
postgresql_listen_addresses: "localhost,{{ ansible_host }}"
postgresql_conf_name: aurora
postgresql_users:
  - name: "{{ aurora_db_user }}"
  - name: aurora_reporting
postgresql_databases:
  - name: "{{ aurora_db_name }}"
    owner: "{{ aurora_db_user }}"
  - name: aurora_analytics
    owner: aurora_reporting
postgresql_hba_clients: "{{ groups['webservers'] | map('extract', hostvars, 'ansible_host') | list }}"
postgresql_hba_database: "{{ aurora_db_name }}"
postgresql_hba_user: "{{ aurora_db_user }}"
  • postgresql_conf_name: aurora keeps the current file, conf.d/aurora.conf.
  • postgresql_hba_clients builds the list of web server IPs in the inventory, which is what knows about the groups. The expression takes the groups['webservers'] list (['web1', 'web2']) and, with the map('extract', hostvars, 'ansible_host') filter, replaces each name with hostvars[name]['ansible_host']; list turns the result into a list: ['192.168.56.11', '192.168.56.12']. Filters are studied in depth in Lesson 5.3. If you add web3 tomorrow, it will get its rule without touching anything else.
  • postgresql_version, postgresql_port, postgresql_max_connections and postgresql_shared_buffers match the role's default values. You could remove them, but they stay for two reasons: they explicitly document Aurora's configuration and, above all, the web servers read db1's postgresql_port through hostvars (Lesson 3.5). A role's defaults aren't part of hostvars: they only exist while the role is running. Whatever other hosts need to read must be in the inventory.

Check the new list:

ansible db1 -m ansible.builtin.debug -a 'var=postgresql_hba_clients'
db1 | SUCCESS => {
    "postgresql_hba_clients": [
        "192.168.56.11",
        "192.168.56.12"
    ]
}

  1. Applying the new roles and verifying

dbservers.yml shrinks to applying the role and checking the result:

---
- name: Configure the Aurora Store database servers
  hosts: dbservers
  become: true

  roles:
    - postgresql

  post_tasks:
    - name: Check that PostgreSQL accepts connections
      community.postgresql.postgresql_ping:
      become_user: postgres

In webservers.yml, delete the pre_tasks section (the role now updates the cache) and the tasks that have moved to the nginx role (installation, site, default site, service, temporary reload and the three firewall ones), and add roles:. The store website tasks stay in tasks: for now; in Lesson 4.4 they'll form the aurora_app role:

---
- name: Configure the Aurora Store web servers
  hosts: webservers
  become: true

  vars:
    aurora_db_server: "{{ groups['dbservers'][0] }}"
    aurora_db_host: "{{ hostvars[aurora_db_server]['ansible_host'] }}"
    aurora_db_port: "{{ hostvars[aurora_db_server]['postgresql_port'] }}"

  roles:
    - nginx

  tasks:
    # These six tasks stay as they were (they'll form the aurora_app role in Lesson 4.4):
    # - Create the web root directory
    # - Publish the store home page
    # - Publish the store static pages
    # - Compute the database connection string
    # - Create the Aurora configuration directory
    # - Publish the database connection details

  post_tasks:
    # ... unchanged: wait, nginx version and assert (Lesson 3.7) ...

Bear in mind that in a play roles run before the tasks in tasks:, whatever order they're written in (you'll study the complete order in Lesson 4.4). That's why nginx is configured before the root directory is created: on servers that are already configured nothing changes, and on a new one it isn't a problem either, because nginx accepts a root that doesn't exist yet (it would simply respond 404 until the page is published).

Check the task list and idempotency:

ansible-playbook site.yml --syntax-check
ansible-playbook webservers.yml --list-tasks
  play #1 (webservers): Configure the Aurora Store web servers	TAGS: []
    tasks:
      nginx : Install nginx	TAGS: []
      nginx : Configure the site in nginx	TAGS: []
      nginx : Enable the site	TAGS: []
      nginx : Disable the default nginx site	TAGS: []
      nginx : Ensure nginx is started and enabled	TAGS: []
      nginx : Reload nginx if its configuration has changed (temporary)	TAGS: []
      nginx : Allow SSH through the firewall	TAGS: []
      nginx : Allow HTTP through the firewall	TAGS: []
      nginx : Enable the firewall	TAGS: []
      Create the web root directory	TAGS: []
      Publish the store home page	TAGS: []
      Publish the store static pages	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: []
ansible-playbook site.yml --check --diff
ansible-playbook site.yml
PLAY RECAP *********************************************************************
db1                        : ok=...  changed=0    unreachable=0    failed=0    ...
web1                       : ok=...  changed=0    unreachable=0    failed=0    ...
web2                       : ok=...  changed=0    unreachable=0    failed=0    ...

changed=0: both roles reproduce the previous configuration exactly. Notice the pg_hba detail: although the task now loops over IP addresses instead of host names, the resulting rules are the same, and the module doesn't change anything. Save the work:

git add roles/nginx roles/postgresql webservers.yml dbservers.yml inventory/
git commit -m "nginx and postgresql roles from webservers.yml and dbservers.yml"

  1. First improvement: a file from files/

With the migration verified, you can now improve the role. Ubuntu's nginx comes with gzip compression enabled only for HTML; the directives for also compressing text, CSS, JavaScript or JSON are commented out in /etc/nginx/nginx.conf. The main file includes everything in /etc/nginx/conf.d/*.conf, so adding a file of your own there is enough. It's fixed content, with no variables: the ideal case for files/.

Create roles/nginx/files/gzip.conf:

# Managed by Ansible (aurora-infra). Do not edit by hand.
# gzip compression for text responses (HTML is already compressed by default).
gzip_vary on;
gzip_proxied any;
gzip_comp_level 5;
gzip_types text/plain text/css application/javascript application/json image/svg+xml;
  • gzip_vary on adds the Vary: Accept-Encoding header, which tells intermediate caches that the response depends on whether the client accepts compression.
  • gzip_types lists the types that are compressed in addition to text/html (which must not be repeated: nginx would warn about a duplicate type).

Add to the role, right after Install nginx, the task that publishes it:

- name: Publish the gzip compression configuration
  ansible.builtin.copy:
    src: gzip.conf
    dest: "{{ nginx_conf_d_dir }}/gzip.conf"
    owner: root
    group: root
    mode: "0644"
  register: nginx_gzip_config

And extend the temporary reload's condition so it takes the new file into account. With four conditions, the line is very long: use the >- folded block (Lesson 3.6):

- name: Reload nginx if its configuration has changed (temporary)
  ansible.builtin.systemd_service:
    name: "{{ nginx_service }}"
    state: reloaded
  when: >-
    nginx_gzip_config is changed or
    nginx_site_config is changed or
    nginx_site_enabled is changed or
    nginx_default_site is changed

This ever-longer condition is the best demonstration of why handlers exist: in Lesson 5.1 each configuration task will simply "notify" that nginx needs to be reloaded.

Before applying it, check what happens today with robots.txt, which is text/plain:

curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' http://192.168.56.11/robots.txt | grep -i -e content-encoding -e vary

It shows nothing: robots.txt is served uncompressed. Simulate and apply only the web servers:

ansible-playbook webservers.yml --check --diff
ansible-playbook webservers.yml
TASK [nginx : Publish the gzip compression configuration] **********************
changed: [web1]
changed: [web2]
...
TASK [nginx : Reload nginx if its configuration has changed (temporary)] *******
changed: [web1]
changed: [web2]
...
PLAY RECAP *********************************************************************
web1                       : ok=...  changed=2    unreachable=0    failed=0    ...
web2                       : ok=...  changed=2    unreachable=0    failed=0    ...

Repeat the request:

curl -s -o /dev/null -D - -H 'Accept-Encoding: gzip' http://192.168.56.11/robots.txt | grep -i -e content-encoding -e vary
Vary: Accept-Encoding
Content-Encoding: gzip

A second run of site.yml must give changed=0 again. Save the work:

ansible-playbook site.yml
git add roles/nginx
git commit -m "nginx role: gzip compression from files/"

Role structure at the end of the lesson:

roles/
├── common/
│   ├── README.md
│   ├── defaults/main.yml
│   ├── meta/main.yml
│   ├── tasks/main.yml
│   └── vars/main.yml
├── nginx/
│   ├── README.md
│   ├── defaults/main.yml
│   ├── files/
│   │   └── gzip.conf
│   ├── meta/main.yml
│   ├── tasks/main.yml
│   └── vars/main.yml
└── postgresql/
    ├── README.md
    ├── defaults/main.yml
    ├── meta/main.yml
    ├── tasks/main.yml
    └── vars/main.yml

Common Mistakes and Tips

  • Could not find or access 'file': the file isn't in the role's files/ (or templates/), it has another name or a typo in the extension. Read the "Searched in" list: it tells you exactly where it looked.
  • Writing src: roles/nginx/files/gzip.conf or src: files/gzip.conf: it sometimes works by chance and fails at other times (for example, when the role is installed in another path). Use just the file name.
  • Creating vars/main.yml with a parameter the inventory needs to change: the inventory value is ignored without warning. Package names and imposed paths go in vars/; anything configurable, in defaults/.
  • Relying on a role's defaults from another host: hostvars['db1']['postgresql_port'] only exists if the variable is in the inventory. A role's default values aren't part of hostvars.
  • Empty directories or main.yml files with only a comment: they do no harm, but they're confusing. Remove what you don't use.
  • Expecting galaxy_info.platforms to prevent the role from running on another system: it's purely informational. If a role doesn't support a system, it must check that itself (in Lesson 4.5 you'll see how to do it naturally when loading each distribution's variables).
  • Tip: when you turn a playbook into a role, first list in a table "current value → role variable → value in the inventory". It's your migration plan and, later, the basis of the README.md.

Exercises

Without running anything, answer: if you change the task in the nginx role to src: conf/gzip.conf, at what exact path would you have to save the file for it to be found first? And if both roles/nginx/files/gzip.conf and ~/aurora-infra/files/gzip.conf existed, which would the role use?

Exercise 2: A maintenance page from files/

Add to the nginx role a static file files/maintenance.html (a simple page with the text "Back soon") and a task that copies it to {{ nginx_root }}/maintenance.html with 0644 permissions. Apply the change only on web2 and check it with curl. Then remove it properly from the server and from the role.

Exercise 3: Reviewing a role's design

A colleague proposes this task for the postgresql role. Find at least three design problems based on what you've seen in this module and fix it:

- name: Configure the parameters
  ansible.builtin.copy:
    dest: /etc/postgresql/16/main/conf.d/aurora.conf
    content: |
      listen_addresses = 'localhost,{{ hostvars['db1']['ansible_host'] }}'
      max_connections = {{ max_conn }}

Solutions

Exercise 1. In roles/nginx/files/conf/gzip.conf: the relative path is appended to each directory in the search list, starting with the role's files/. If both files existed, the role would use roles/nginx/files/gzip.conf, because the role's files/ is searched before files/ next to the playbook.

Exercise 2. roles/nginx/files/maintenance.html:

<!DOCTYPE html>
<html lang="en">
<head><meta charset="utf-8"><title>Maintenance</title></head>
<body><h1>Back soon</h1></body>
</html>

The task, for example after Enable the site:

- name: Publish the maintenance page
  ansible.builtin.copy:
    src: maintenance.html
    dest: "{{ nginx_root }}/maintenance.html"
    owner: root
    group: root
    mode: "0644"
ansible-playbook webservers.yml --limit web2
curl -s http://192.168.56.12/maintenance.html

There's no need to reload nginx: it's content, not configuration. To remove it, change the task to ansible.builtin.file with path: "{{ nginx_root }}/maintenance.html" and state: absent, run it again and then delete the task and the file from files/. (On reflection, a store page fits better in the aurora_app role you'll create in Lesson 4.4: nginx should stick to the web server.)

Exercise 3. Problems:

  1. The path has the version (16) and the name aurora hardcoded: they should come from postgresql_config_dir (internal, built with postgresql_version) and from postgresql_conf_name.
  2. It reads the inventory directly (hostvars['db1']): the role is tied to a host called db1. The address must arrive through a variable (postgresql_listen_addresses).
  3. max_conn doesn't have the role's prefix: it could clash with another variable in the play, and it's unclear which role it belongs to.
  4. In addition, owner, group and mode are missing, as is the register needed for the temporary restart.
- name: Configure the PostgreSQL parameters
  ansible.builtin.copy:
    dest: "{{ postgresql_config_dir }}/conf.d/{{ postgresql_conf_name }}.conf"
    owner: postgres
    group: postgres
    mode: "0644"
    content: |
      # Managed by Ansible (aurora-infra). Do not edit by hand.
      listen_addresses = '{{ postgresql_listen_addresses }}'
      max_connections = {{ postgresql_max_connections }}
  register: postgresql_config

Conclusion

You now know the complete anatomy of a role: tasks/ and handlers/ with their main.yml, defaults/ and vars/ with their different precedences, files/ and templates/ as stores of material for the servers, meta/main.yml with galaxy_info (informational) and dependencies, the future meta/argument_specs.yml, the custom code directories and tests/. You know how Ansible looks for a relative path inside a role (first the role's files/ or templates/, then the role itself and, finally, next to the playbook) and you've applied all of this to Aurora Store: the nginx and postgresql roles reproduce, without a single change, what webservers.yml and dbservers.yml used to do, they receive their data from the inventory (including the list of PostgreSQL client IPs, which the role no longer computes) and nginx distributes its first file from files/. But the playbooks are still halfway there: webservers.yml mixes a role with loose tasks. In the next lesson, Using Roles in Playbooks, you'll study the roles: keyword in depth, the execution order of a play, how to pass parameters to roles and their precedence, you'll create the aurora_app role and you'll trim Aurora's playbooks down to the essentials.

© Copyright 2026. All rights reserved