Skip to main content

Infrastructure as code · Intermediate · 20 min

Organise Ansible work into reusable roles

By Padding · Updated 18 Nov 2026
Ubuntu 26.04 · Ansible 15.0.0 (ansible-core 2.22)

You will split a one-file Ansible playbook into a base role and a web role, pull in a pinned community role from requirements.yml, and finish with a site.yml that runs cleanly a second time with changed=0.

On this page

A playbook that sets up one kind of server starts small and stays readable for a while. Then a second kind of server needs the same base packages, someone copies the first ten tasks into a new file, and the two copies drift apart. Roles fix this. A role is a folder with a fixed layout: its tasks, the handlers those tasks notify, the templates and files they copy, its default settings and the other roles it needs. Any play can apply it by name.

In this tutorial you take the shape of the playbook from /tutorials/configure-a-server-with-an-ansible-playbook (base packages, Nginx, one templated page and a reload handler) and split it into two roles: base, for what every server gets, and web, for Nginx. You make web depend on base, add a community role at a pinned version, learn when to import a role and when to include one, and end with a site.yml you can run any number of times.

Step 1 · Install Ansible 15 and set up the project

Install Ansible from PyPI with pipx, pinned so your output matches this page. Ansible 15.0.0 bundles ansible-core 2.22 and needs Python 3.13 or newer; Ubuntu 26.04 ships a newer Python than that. If you installed Ansible 14 for the earlier tutorial, run pipx install --force --include-deps ansible==15.0.0 instead, because plain pipx install leaves an existing installation unchanged:

Bash
sudo apt update
sudo apt install -y pipx openssh-client
pipx install --include-deps ansible==15.0.0
export PATH="$HOME/.local/bin:$PATH"
ansible --version | head -n 1

The last line starts with ansible [core 2.22.. Add the PATH line to ~/.bashrc (or run pipx ensurepath) so the commands are found in new terminals. This install gets no updates from apt; upgrade it with pipx upgrade ansible when you choose to.

Make a project folder with a config file, so you do not have to pass -i inventory.ini to every command. roles_path tells Ansible to look for roles in roles/ (the ones you write) and vendor_roles/ (the ones you download):

Bash
mkdir -p ~/ansible-roles-demo
cd ~/ansible-roles-demo
cat > ansible.cfg <<'CFG'
[defaults]
inventory = inventory.ini
roles_path = roles:vendor_roles
CFG

Now the inventory. Replace the address and user with your server's (203.0.113.10 is a documentation address and will not connect):

Bash
cat > inventory.ini <<'INI'
[web]
web1 ansible_host=203.0.113.10

[web:vars]
ansible_user=deploy
ansible_python_interpreter=/usr/bin/python3
INI
export WEB_HOST=203.0.113.10   # the same address, for the curl checks later

For reference, this is the shape of the single playbook you are about to take apart. You do not need to create it:

YAML
- name: Set up the web server
  hosts: web
  become: true
  vars:
    site_title: Hello from Ansible
  tasks:
    - name: Install base packages      # every server needs these
    - name: Write the login message    # every server needs this
    - name: Install Nginx              # only web servers
    - name: Write the home page        # only web servers, notifies the handler
    - name: Make sure Nginx is running # only web servers
  handlers:
    - name: Reload Nginx

Two jobs are mixed in one file: what every server gets, and what only a web server gets. Each becomes a role.

Check it worked

Bash
ansible web -m ping

web1 answers SUCCESS with "ping": "pong", and you did not pass -i, which shows ansible.cfg was read. Ansible ignores an ansible.cfg in a folder anyone can write to, so keep the project in your home directory.

Step 2 · Generate the role skeletons

ansible-galaxy role init creates a role folder with the standard layout. Make one for each job:

Bash
mkdir -p roles
ansible-galaxy role init --init-path roles base
ansible-galaxy role init --init-path roles web

Each folder Ansible recognises has a fixed purpose:

  • tasks/main.yml is what runs when the role is applied.
  • handlers/main.yml holds handlers the role's tasks can notify.
  • templates/ holds Jinja2 files for the template module, and files/ holds files copied as they are. Inside a role, src: motd finds files/motd without a path.
  • defaults/main.yml holds settings a caller is expected to change. They have the lowest precedence of any variable, so an inventory value or a play value replaces them.
  • vars/main.yml holds values the role relies on and callers should not touch. They outrank inventory and play variables; only a few sources such as extra vars (-e) beat them.
  • meta/main.yml describes the role and lists the roles it depends on.

You can delete any folder a role does not use. tests/ is for a quick test play; leave it for now.

Check it worked

Bash
ls roles/web

The listing includes defaults, files, handlers, meta, tasks, templates, tests, vars and a README.md.

Step 3 · Fill in the base role

The base role installs a short list of packages and writes a login message. The package list goes in defaults, with a second empty list that callers can add to without repeating the whole default list:

Bash
cat > roles/base/defaults/main.yml <<'YAML'
# Packages every server gets. Override base_packages to replace the list,
# or set base_extra_packages to add to it.
base_packages:
  - ca-certificates
  - curl
  - htop
base_extra_packages: []
YAML

cat > roles/base/files/motd <<'TXT'
This server is managed by Ansible. Changes made by hand may be overwritten.
TXT

cat > roles/base/tasks/main.yml <<'YAML'
- name: Install base packages
  ansible.builtin.apt:
    name: "{{ base_packages + base_extra_packages }}"
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: Write the login message
  ansible.builtin.copy:
    src: motd
    dest: /etc/motd
    owner: root
    group: root
    mode: "0644"
YAML

Prefix every variable with the role name (base_, web_). Variables in Ansible share one namespace across a play, so a plain packages in one role could be silently replaced by a packages from another.

Now a first site.yml that applies only this role. A roles: list in a play is all it takes; Ansible finds roles/base through roles_path. The copy task replaces /etc/motd, so if your server already has a message there you want to keep, save it first:

Bash
cat > site.yml <<'YAML'
- name: Configure web servers
  hosts: web
  become: true
  roles:
    - base
YAML
ansible-playbook site.yml

Task names in the output now carry the role, such as TASK [base : Install base packages], so you can see which role did what.

Check it worked

Bash
ansible web -a "cat /etc/motd"

web1 prints CHANGED with the line This server is managed by Ansible. (the ad hoc command module always reports a change, even though it only reads a file). The recap of the ansible-playbook site.yml run before it shows failed=0.

Step 4 · Fill in the web role

The web role is where the difference between defaults and vars matters. The page title is something each caller will want to set, so it goes in defaults. The package name, service name and web root are facts about Nginx on Ubuntu that the tasks depend on, so they go in vars, where an inventory value cannot change them by accident:

Bash
cat > roles/web/defaults/main.yml <<'YAML'
# Settings callers may override from inventory or the play.
web_site_title: Hello from a role
YAML

cat > roles/web/vars/main.yml <<'YAML'
# Internal values the tasks rely on. Not meant to be overridden.
web_package: nginx
web_service: nginx
web_root: /var/www/html
YAML

cat > roles/web/templates/index.html.j2 <<'HTML'
<!doctype html>
<html lang="en">
<head><meta charset="utf-8"><title>{{ web_site_title }}</title></head>
<body>
  <h1>{{ web_site_title }}</h1>
  <p>Served by the web role on {{ inventory_hostname }}.</p>
</body>
</html>
HTML

cat > roles/web/handlers/main.yml <<'YAML'
- name: Reload Nginx
  ansible.builtin.service:
    name: "{{ web_service }}"
    state: reloaded
YAML

cat > roles/web/tasks/main.yml <<'YAML'
- name: Install Nginx
  ansible.builtin.apt:
    name: "{{ web_package }}"
    state: present
    update_cache: true
    cache_valid_time: 3600

- name: Write the home page
  ansible.builtin.template:
    src: index.html.j2
    dest: "{{ web_root }}/index.html"
    owner: root
    group: root
    mode: "0644"
  notify: Reload Nginx

- name: Make sure Nginx is running and starts at boot
  ansible.builtin.service:
    name: "{{ web_service }}"
    state: started
    enabled: true
YAML

The template task names index.html.j2 with no folder, because inside a role the template module looks in that role's templates/. The handler lives in the role too, so the role carries everything it needs. Add the role to the play and run it:

Bash
cat > site.yml <<'YAML'
- name: Configure web servers
  hosts: web
  become: true
  roles:
    - base
    - web
YAML
ansible-playbook site.yml

The base tasks report ok, because the server already matches. The Nginx install and the page report changed, and RUNNING HANDLER [web : Reload Nginx] appears at the end.

Check it worked

Bash
curl -s "http://$WEB_HOST/" | grep "<h1>"

The line reads <h1>Hello from a role</h1>, the value from defaults. If port 80 is closed by the server's firewall, run the same curl on the server against http://127.0.0.1/.

Step 5 · Declare that web depends on base

Right now web only works because site.yml happens to list base first. Anyone who writes a play with just web gets Nginx on a server without your base setup. Say so in the role itself, in meta/main.yml. Replace both generated meta files with short ones:

Bash
cat > roles/base/meta/main.yml <<'YAML'
galaxy_info:
  author: your-team
  description: Packages and settings every server gets
  license: MIT
  min_ansible_version: "2.22"
dependencies: []
YAML

cat > roles/web/meta/main.yml <<'YAML'
galaxy_info:
  author: your-team
  description: Nginx serving one templated page
  license: MIT
  min_ansible_version: "2.22"
dependencies:
  - role: base
YAML

Ansible runs a role's dependencies before the role. It also runs a role only once per play unless it is given different role parameters, so site.yml can keep listing base and web and base still runs once. To see the dependency at work, write a play that names only web and list its tasks without running them:

Bash
cat > web-only.yml <<'YAML'
- name: Web role on its own
  hosts: web
  become: true
  roles:
    - web
YAML
ansible-playbook web-only.yml --list-tasks

Use dependencies for what a role cannot work without. If two roles merely tend to go together, list both in the play instead; a dependency is applied every time, wherever the role is used.

Check it worked

The task list starts with base : Install base packages and base : Write the login message, then the three web : tasks, although web-only.yml never mentions base. Remove the demo play when you have read it:

Bash
ansible-playbook web-only.yml --list-tasks | grep "base : Install base packages"
rm web-only.yml

Step 6 · Install a community role at a pinned version

You do not have to write every role. Ansible Galaxy hosts roles others maintain. Describe the ones you use in requirements.yml, with an exact version, so every machine that installs them gets the same code. This one installs Git:

Bash
cat > requirements.yml <<'YAML'
roles:
  - name: geerlingguy.git
    version: 3.0.1
YAML
ansible-galaxy role install -r requirements.yml -p vendor_roles
printf 'vendor_roles/\n' > .gitignore

-p vendor_roles puts the download next to your own roles instead of in ~/.ansible/roles. The .gitignore keeps downloaded code out of your repository; requirements.yml is what you commit, and a teammate or a pipeline runs the same install command to get identical roles. On prepaid or metered data, install once per machine and reuse the folder; the download is small, and a pinned version means there is nothing to fetch again until you change the pin.

Read a community role before you run it with become: true. It runs as root on your servers. Open vendor_roles/geerlingguy.git/tasks/main.yml: on Ubuntu it updates the apt cache and installs the git package, and its defaults/main.yml shows what you can change, such as git_packages. Roles that have not been updated for a while can print deprecation warnings on a new ansible-core; read them, because a warning in one release can be an error a few releases later.

Check it worked

Bash
ansible-galaxy role list | grep "geerlingguy.git"

The line reads - geerlingguy.git, 3.0.1, under the vendor_roles path.

Step 7 · Choose between import_role and include_role

A roles: list is one way to apply a role. You can also apply one as a task, which lets you put it between other tasks. There are two modules, and they behave differently:

  • ansible.builtin.import_role is static. Ansible reads the role's tasks when it parses the playbook, as if you had pasted them in. Their names show in --list-tasks, --start-at-task can jump to them, and a when or tags on the import is copied onto every task in the role. You cannot loop over an import, or take the role name from a host variable.
  • ansible.builtin.include_role is dynamic. Ansible reaches the task at run time and only then loads the role. A when on it is checked once, to decide whether to load the role at all, and it can run in a loop or take its name from a variable. Its tasks do not show in --list-tasks, and tags on the include apply only to the include unless you add apply:.

See the difference with two small plays that apply the Git role each way:

Bash
cat > import-demo.yml <<'YAML'
- name: Static import
  hosts: web
  become: true
  tasks:
    - name: Install Git with the community role
      ansible.builtin.import_role:
        name: geerlingguy.git
YAML

cat > include-demo.yml <<'YAML'
- name: Dynamic include
  hosts: web
  become: true
  tasks:
    - name: Install Git with the community role
      ansible.builtin.include_role:
        name: geerlingguy.git
YAML

ansible-playbook import-demo.yml --list-tasks > import-tasks.txt
ansible-playbook include-demo.yml --list-tasks > include-tasks.txt
cat import-tasks.txt include-tasks.txt

A rule that holds up: import by default, because you can see and filter everything before it runs. Include when the decision depends on something only known at run time, such as a fact gathered from the host or a list you loop over.

Check it worked

The import listing shows the role's own tasks, such as geerlingguy.git : Ensure git is installed (Debian).. The include listing shows only Install Git with the community role:

Bash
grep "geerlingguy.git : Ensure git is installed (Debian)" import-tasks.txt
grep "Install Git with the community role" include-tasks.txt
rm import-demo.yml include-demo.yml import-tasks.txt include-tasks.txt

Step 8 · Write the final site.yml and run it twice

The final play applies base and web through roles: and adds Git with include_role, behind a switch so a group of servers can turn it off. Set your own values in inventory rather than in the roles: a group_vars/web.yml file next to the playbook applies to every host in the web group and outranks the role defaults:

Bash
cat > site.yml <<'YAML'
- name: Configure web servers
  hosts: web
  become: true
  roles:
    - base
    - web
  tasks:
    - name: Install Git with the community role
      ansible.builtin.include_role:
        name: geerlingguy.git
      when: install_git | default(true) | bool
YAML

mkdir -p group_vars
cat > group_vars/web.yml <<'YAML'
web_site_title: Shop front
base_extra_packages:
  - jq
install_git: true
YAML

ansible-playbook site.yml | tee run1.log

In a play, roles listed under roles: run before the play's tasks:, so Git is installed last. This run changes the page (new title), installs jq and Git, and reloads Nginx. Base appears once in the output even though web depends on it and the play lists it too.

Now run it again:

Bash
ansible-playbook site.yml | tee run2.log
grep "changed=0" run2.log

Check it worked

The second recap reads ok= some number, changed=0, failed=0. Every task found the server already in the state the roles describe. Check the results on the server:

Bash
curl -s "http://$WEB_HOST/" | grep "<h1>"
ansible web -a "git --version"
ansible web -a "jq --version"

The heading is now <h1>Shop front</h1>, from group_vars, and the two version commands print git version and jq- followed by version numbers.

Your project now looks like this, and it is the layout to commit (everything except vendor_roles/ and the .log files):

Text
ansible-roles-demo/
├── ansible.cfg
├── inventory.ini
├── group_vars/web.yml
├── requirements.yml
├── site.yml
└── roles/
    ├── base/  (defaults, files, meta, tasks)
    └── web/   (defaults, vars, templates, handlers, meta, tasks)

To remove what this tutorial put on the server, stop and purge Nginx and jq, and delete the page and the login message. This deletes /etc/motd, so only run it on the demo server. curl, htop and Git are left in place because many servers already have them; remove them too if yours did not:

Bash
ansible web -b -m ansible.builtin.service -a "name=nginx state=stopped"
ansible web -b -m ansible.builtin.apt -a "name=nginx,jq state=absent purge=true autoremove=true"
ansible web -b -m ansible.builtin.file -a "path=/var/www/html/index.html state=absent"
ansible web -b -m ansible.builtin.file -a "path=/etc/motd state=absent"

Each command reports CHANGED for web1. Delete the project with rm -rf ~/ansible-roles-demo and remove Ansible with pipx uninstall ansible when you no longer need them.

Next steps

  • Move the page and an Nginx server block into richer templates: /tutorials/template-config-files-with-ansible-jinja2-and-handlers
  • Learn where each variable belongs and which value wins: /tutorials/organise-ansible-variables-with-group-vars-and-host-vars
  • Lint the roles and test them with Molecule: /tutorials/test-ansible-roles-with-ansible-lint-and-molecule
  • Revisit the single-playbook starting point: /tutorials/configure-a-server-with-an-ansible-playbook

Need this done for you?

Padding does this work for growing companies, from the first diagnosis to a system that keeps working.

Platform Engineering

Get new tutorials

New tutorials, about twice a month.