Ansible Role Creation
A role is a directory layout that Ansible knows how to read: tasks here, templates there, variables in two places with different precedence. ansible-galaxy init creates the skeleton in one command. This fills in the parts that matter, explains the defaults versus vars distinction that decides what callers can change, and deletes the directories you will not use.
Roles and Collections Guide 24 of 45 Intermediate
- OSUbuntu 26.04 LTS
- ansible-core2.20.1
- Python3.14.4
- TimeAbout 16 min
defaults/main.yml has the lowest precedence of any variable in Ansible, and vars/main.yml has a very high one. That is the entire design: defaults are the role's public interface and are meant to be overridden, vars are internal and are not. Putting a tunable value in vars/ makes it effectively unchangeable by the caller.
| Server Name | IP Address | OS | Roles | CPU | RAM | HDD |
|---|---|---|---|---|---|---|
| ANS-CTL01 | 192.168.0.36 | Ubuntu 26.04 LTS | Ansible Control Node | 2 Core | 3 GB | 50 GB |
This guide includes
Use this when a playbook has grown past one file. This matters because a role is a directory layout Ansible already knows how to read - so paths inside it are implicit, and defaults is its public interface.
- generating the skeleton with
ansible-galaxy init - treating
defaultsas the role's public interface - writing the tasks and a handler
- finding that paths inside a role are implicit, with no directory to name
- describing the role in
meta
Before you start
- A control node configured as shown in the first step.
- The session creates
~/pb/roles/webapp/and fills in six files.
-
The configuration this guide assumes
-
The skeleton
-
defaults are the role's public interface
-
The tasks and a handler
-
Paths inside a role are implicit
-
meta describes the role