RH294 Ch 9: Roles, Collections and RHEL System Roles
Roles package tasks, handlers, templates, files and variables under a standard directory tree so the same logic can be reused across plays and projects. Create the skeleton with:
bash cd ~/ansible/roles && ansible-galaxy role init motd
That creates tasks/, handlers/, templates/, files/, vars/, defaults/, meta/ and tests/. defaults/main.yml holds variables the user is expected to override (lowest precedence); vars/main.yml holds internal values that are hard to override. Inside a role, template: src: motd.j2 looks in the role's own templates/. Use it from a play with roles: (runs before tasks:) or with importrole / includerole as a task:
yaml - hosts: prod roles: - role: baseline baselinebanner: Authorized use only
Installing roles. A requirements file lists sources — Git URLs, tarball URLs or Galaxy names — with an optional name:
yaml - src: http://utility/roles/baseline.tar.gz name: baseline
ansible-galaxy role install -r roles/requirements.yml -p roles.
Collections ship modules, plugins and roles under a namespace, e.g. ansible.posix.firewalld or community.general.inifile. Install them from a collections/requirements.yml:
yaml collections: - name: http://utility/collections/ansible-posix-1.6.2.tar.gz type: url
ansible-galaxy collection install -r collections/requirements.yml -p collections, and set collectionspath = ./collections:/usr/share/ansible/collections in ansible.cfg so both the project's and the system collections are found. ansible-galaxy collection list confirms it. Always call modules by their fully qualified collection name.
RHEL system roles come from the rhel-system-roles package as the collection redhat.rhelsystemroles (timesync, selinux, network, storage, firewall, …). Each has a README and examples under /usr/share/doc/rhel-system-roles/. Copy the example, change the variables:
yaml - hosts: all vars: timesyncntpservers: - hostname: utility.lab.example.com iburst: true roles: - redhat.rhelsystemroles.timesync
Common exam mistakes - Overriding collectionspath with only ./collections, which hides the system roles. - Installing roles or collections into the default home directory instead of the path the task names. - Misspelled variable names for system roles (they fail silently and use defaults) — copy them from the README. - Putting role variables in vars/ when the task says the user must be able to override them.