Lesson 11 of 11 ↓
- 1.Ansible Basic Setup Guide
- 2.Ansible Inventory Guide (hosts)
- 3.Ansible Configuration Guide (ansible.cfg)
- 4.Ansible Ad-hoc Commands Guide
- 5.Ansible Playbook Guide (playbook.yml)
- 6.Ansible Variables & Precedence Guide
- 7.Ansible Loops Guide
- 8.Ansible Conditionals Guide (when)
- 9.Ansible Vault Guide
- 10.Ansible Handlers Guide
- 11.Ansible Custom Roles Guide
4 min read
Ansible Custom Roles Guide
A comprehensive guide to creating, structuring, and using Custom Roles in Ansible. Roles are the best way to organize your code, making it reusable, shareable, and clean.
What is an Ansible Role?
A Role is a package of automation. Instead of writing one giant playbook with 100 tasks, variables, and handlers, you split them into specific folders.
-
Analogy: If a Playbook is a "Recipe", a Role is a "Pre-packaged Ingredient" (like a jar of sauce) that you just add to the recipe.
-
Benefits:
-
Reusability: Write once, use in many playbooks.
-
Structure: Standardized directory layout.
-
Sharing: Easily shareable via Ansible Galaxy.
-
Step 1: Create Role Structure (ansible-galaxy)
Ansible comes with a tool called ansible-galaxy that can "scaffold" (automatically create) the folder structure for you.
Command:
ansible-galaxy init nginxDetailed Explanation
-
ansible-galaxy: The CLI tool for managing roles. -
init: The command to initialize a new role structure locally. -
nginx: The name of the role you want to create. -
Result: It creates a folder named
nginxin your current directory with all the standard subfolders (tasks, handlers, vars, etc.) ready for you to fill.
Step 2: Project Directory Structure
After running the command, your project should look like this. Here is what every folder does:
my-ansible-project/
├── inventory # Your hosts file
├── site.yml # The "Master" playbook
└── roles/
└── nginx/ # The Role Directory
├── tasks/ # ✅ MAIN LOGIC: Steps to install/config
│ └── main.yml # The entry point for tasks
├── handlers/ # ✅ EVENTS: Restart logic
│ └── main.yml
├── defaults/ # ✅ WEAK VARS: Default variables (easy to override)
│ └── main.yml
├── vars/ # ✅ STRONG VARS: Variables meant to be constant
│ └── main.yml
├── files/ # ✅ STATIC FILES: Files to copy (scripts, certs)
├── templates/ # ✅ DYNAMIC FILES: Jinja2 templates (.j2)
└── meta/ # ✅ METADATA: Role info & dependencies
└── main.ymlPro Tip: defaults vs vars
-
defaults/main.yml: Use this for variables you want the user to allow changing easily (e.g.,nginx_port: 80). They have lowest priority. -
vars/main.yml: Use this for variables internal to the role logic that shouldn't be changed often. They have high priority.
Step 3: Define Tasks in Role
The tasks/main.yml file is the heart of the role. It executes the actual automation.
File: roles/nginx/tasks/main.yml
---
# Task 1: Install the Package
- name: Install nginx
yum:
name: nginx
state: present
# Task 2: Manage the Service
- name: Start and enable nginx
service:
name: nginx
state: started
enabled: trueArgument Explanation
-
yumModule:-
name: nginx: The package name to install. -
state: present: Ensures it is installed.
-
-
serviceModule:-
name: nginx: The service daemon name. -
state: started: Ensures it's running right now. -
enabled: true: Crucial. Ensures it starts automatically if the server reboots (systemctl enable).
-
Step 4: Define Handlers (optional)
Handlers are used to restart services only when configuration changes.
File: roles/nginx/handlers/main.yml
---
- name: restart nginx
service:
name: nginx
state: restartedArgument Explanation
-
name: restart nginx: This is the "Trigger Name". You must use this exact string in your tasks (e.g.,notify: restart nginx). -
state: restarted: Stops and starts the service to apply new configs.
Step 5: Create the Playbook (site.yml)
Now that the role is built, you need a Playbook to "call" or "use" it. This file is usually much shorter because the logic is hidden inside the role.
File: site.yml (in project root)
---
- name: Apply nginx role to web servers
hosts: all # Target hosts from inventory
become: true # Run as root (sudo)
roles:
- nginx # The name of the folder inside /roles/Detailed Explanation
roles:: This section tells Ansible to look into theroles/directory, find a folder namednginx, and executetasks/main.yml. It also automatically loads any vars, handlers, or defaults found inside that role.
Step 6: Run the Playbook
Finally, execute the automation.
Command:
ansible-playbook -i inventory site.ymlArgument Explanation
-
ansible-playbook: The command to run YAML playbooks. -
-i inventory: Specifies the inventory file path. -
site.yml: The master playbook file.
Summary Checklist for Custom Roles
-
Init:
ansible-galaxy init <role_name> -
Tasks: Write logic in
tasks/main.yml. -
Handlers: Write restart logic in
handlers/main.yml. -
Vars: Define defaults in
defaults/main.yml. -
Playbook: Call the role using the
roles:section. -
Run: Execute with
ansible-playbook.
Bonus: Finding Community Roles (ansible Galaxy Web)
You don't always have to write roles from scratch. You can find high-quality, pre-made roles on the official website.
Website: https://galaxy.ansible.com/ui/
Steps to find the best roles:
-
Visit the Site: Go to the link above.
-
Navigate: Click on Roles in the menu.
-
Search: Type the technology you need (e.g.,
redis,postgresql,docker). -
Sort by Popularity (Crucial Step):
-
By default, it might sort by "Created" (newest).
-
Change the sort filter to "Download Count".
-
Why? This helps you find the most popular and battle-tested roles used by the community, rather than obscure or untested ones.
-
-
Install: Copy the installation command provided on the role page (e.g.,
ansible-galaxy install geerlingguy.nginx).
Comments
Loading the discussion…