Skip to content

Expert · Ansible in depth · topic 52 of 57 · 35 min

Roles, collections and ansible-galaxy

Explanation

A role packages tasks, handlers, templates, files and default variables in a standard folder layout so you can reuse them, for example an "apache" role. Collections bundle roles, modules and plugins under a namespace, like ansible.posix. ansible-galaxy creates role skeletons and installs roles and collections, often from a requirements.yml file.

Why roles?

A long playbook mixing web, database and firewall tasks is hard to read and impossible to reuse. A role is a self-contained unit for one job ("configure Apache"). Any playbook can then say roles: [apache] and get all its tasks, handlers, templates and defaults. Teams share roles across projects, and the community shares them on Ansible Galaxy.

The role layout

bash
$ cd ~/project/roles
$ ansible-galaxy role init apache
- Role apache was created successfully
$ tree apache
apache
├── defaults/main.yml     # default variables (lowest precedence: meant to be overridden)
├── files/                # static files for copy
├── handlers/main.yml     # handlers
├── meta/main.yml         # author, platforms, dependencies on other roles
├── README.md
├── tasks/main.yml        # the tasks: the entry point
├── templates/            # .j2 templates
├── tests/
└── vars/main.yml         # role variables (high precedence: hard to override)
yaml
# roles/apache/defaults/main.yml
apache_port: 80
apache_admin: webmaster@example.com

# roles/apache/tasks/main.yml
- name: Install Apache
  ansible.builtin.dnf:
    name: httpd
    state: present
- name: Configure Apache
  ansible.builtin.template:
    src: httpd.conf.j2          # found in roles/apache/templates/ automatically
    dest: /etc/httpd/conf/httpd.conf
    mode: "0644"
  notify: Restart Apache
- name: Apache is running
  ansible.builtin.service:
    name: httpd
    state: started
    enabled: true
Inside a role, src paths for template and copy are looked up in the role's templates/ and files/ folders.
yaml
# site.yml
- name: Web tier
  hosts: webservers
  become: true
  roles:
    - role: apache
      vars:
        apache_port: 8080
Roles listed under roles: run before the play's tasks. include_role / import_role call a role from within tasks.

Collections

A collection is a distribution package for Ansible content: modules, roles, plugins and playbooks, named namespace.collection, like ansible.posix, community.general or redhat.rhel_system_roles. Collections are installed from Ansible Galaxy (galaxy.ansible.com), from Red Hat Automation Hub (certified content, needs a subscription), from a private hub, or from tar files.

yaml
# collections/requirements.yml
collections:
  - name: ansible.posix
  - name: community.general
    version: ">=8.0.0"
roles:
  - name: geerlingguy.nginx       # a community role from Galaxy
bash
$ ansible-galaxy collection install -r collections/requirements.yml -p ./collections
$ ansible-galaxy role install -r collections/requirements.yml -p ./roles
$ ansible-galaxy collection list | grep posix
ansible.posix    1.5.4
-p installs into the project, so it travels with your code. Point ansible.cfg at it with collections_path = ./collections and roles_path = ./roles.

With ansible-navigator, collections usually come from the execution environment image; anything extra goes in the project's collections/ folder. Check with ansible-navigator collections.

Common mistakes

  • Putting variables you expect users to change in vars/main.yml. They then cannot override them from group_vars. Use defaults/main.yml for that.
  • Writing templates/httpd.conf.j2 as the src inside a role: the role already looks in templates/, so the src is just httpd.conf.j2.
  • Installing roles into a random path and then "role not found". Set roles_path in ansible.cfg or use -p with the project folder.
  • Using community content blindly in production. Read the role, pin versions, and test.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Roles, collections and ansible-galaxy · 1/6

role = reusable unit

A role packs tasks, handlers, templates, files and defaults into one reusable unit.

Prefer a video by a teacher? Find free videos on “ansible roles tutorial ansible-galaxy collections requirements.yml” on YouTube ↗

In real life: Shared roles across 40 client projects at a managed service provider

A managed service provider in Bengaluru keeps a Git repository of in-house roles: baseline, hardening, monitoring_agent, apache and postgresql. Each client project has a short requirements.yml listing the roles and collections with pinned versions, and a site.yml that just applies roles to groups. A fix in the hardening role reaches all 40 clients when they bump one version number.

yaml
- name: Every server
  hosts: all
  become: true
  roles:
    - baseline
    - hardening
    - monitoring_agent
- name: Web tier
  hosts: webservers
  become: true
  roles:
    - apache

Practice (0/3 done)

Task 1 · Question

Where should a role keep variables that users are expected to override?

Task 2 · Question

Which command creates the folder skeleton for a new role named db?

Task 3 · Practice

Turn your web playbook into a role "apache" with: defaults (apache_port, index_text), a template for /var/www/html/index.html, tasks for package, template, firewall port and service, and a handler. Install ansible.posix from a requirements.yml into the project. Use the role from site.yml with a different port for one group.

Quick quiz

Question 1

1.In a role, where does the template module look for src files by default?

Question 2

2.What is a collection?

Question 3

3.In which order do things run in a play with both roles: and tasks:?

Question 4

4.Which file lists roles and collections to install for a project?

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

In a role, where does the template module look for src files by default?

Answer: templates/

templates/ for template, files/ for copy.

What is a collection?

Answer: A package of Ansible content (modules, roles, plugins) under a namespace

For example ansible.posix.

In which order do things run in a play with both roles: and tasks:?

Answer: roles, then tasks

Roles listed under roles: run first.

Which file lists roles and collections to install for a project?

Answer: requirements.yml

ansible-galaxy install -r requirements.yml.

Which command creates the standard folder skeleton for a new role?Related

Answer: ansible-galaxy role init

ansible-galaxy role init NAME creates tasks, handlers, templates, defaults and the other folders.

From Roles, templates, Galaxy and Vault

Which collection provides the firewalld module?Related

Answer: ansible.posix

ansible.posix.firewalld.

From Everyday modules and handlers

Where are example playbooks for system roles on RHEL?Related

Answer: /usr/share/doc/rhel-system-roles/

Each role has examples and a README there.

From RHEL System Roles and Ansible Vault

What does ansible-playbook site.yml --check --diff do?Related

Answer: Shows what would change, with file differences, without changing anything

Check mode is a dry run; diff shows the before and after of files.

From Ansible playbooks

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 1 more topic in “Ansible in depth” before its exam: RHEL System Roles and Ansible Vault.
  2. Module 10 exam: Ansible in depth · 14 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Certifications and career. 57 topics left in the course before the final exam.

← Previous: Jinja2 templates